You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
fromevolutionapi.models.instanceimportInstanceConfig# Configuração básicaconfig=InstanceConfig(instanceName="minha-instancia",integration="WHATSAPP-BAILEYS",qrcode=True)# Configuração completaconfig=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)
fromevolutionapi.models.presenceimportPresenceConfig,PresenceStatus# Definir como disponívelconfig=PresenceConfig(presence=PresenceStatus.AVAILABLE)# Definir como indisponívelconfig=PresenceConfig(presence=PresenceStatus.UNAVAILABLE)response=client.instance_operations.set_presence(instance_id,config,instance_token)
Sending Messages
Text Message
fromevolutionapi.models.messageimportTextMessage,QuotedMessage# Mensagem simplesmessage=TextMessage(number="5511999999999",text="Olá, como você está?",delay=1000# delay opcional em ms)# Mensagem com mençõesmessage=TextMessage(number="5511999999999",text="@everyone Olá a todos!",mentionsEveryOne=True,mentioned=["5511999999999","5511888888888"])# Mensagem com link previewmessage=TextMessage(number="5511999999999",text="Confira este link: https://exemplo.com",linkPreview=True)# Mensagem com citaçãoquoted=QuotedMessage(key={"remoteJid":"5511999999999@s.whatsapp.net","fromMe":False,"participant":"5511999999999@s.whatsapp.net","id":"123456789","owner":"5511999999999@s.whatsapp.net" })message=TextMessage(number="5511999999999",text="Esta é uma resposta",quoted=quoted)response=client.messages.send_text(instance_id,message,instance_token)
Media Message
fromevolutionapi.models.messageimportMediaMessage,MediaType,QuotedMessage# Mensagem com imagemmessage=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ídeomessage=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 documentomessage=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çõesmessage=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)
Status Message
fromevolutionapi.models.messageimportStatusMessage,StatusType,FontType# Status de textomessage=StatusMessage(type=StatusType.TEXT,content="Meu status de texto",caption="Legenda opcional",backgroundColor="#FF0000",font=FontType.BEBASNEUE_REGULAR,allContacts=True)# Status de imagemmessage=StatusMessage(type=StatusType.IMAGE,content="base64_da_imagem",caption="Minha imagem de status")# Status de vídeomessage=StatusMessage(type=StatusType.VIDEO,content="base64_do_video",caption="Meu vídeo de status")# Status de áudiomessage=StatusMessage(type=StatusType.AUDIO,content="base64_do_audio",caption="Meu áudio de status")response=client.messages.send_status(instance_id,message,instance_token)
fromevolutionapi.models.messageimportPollMessagemessage=PollMessage(number="5511999999999",name="Minha Enquete",selectableCount=1,# número de opções que podem ser selecionadasvalues=["Opção 1","Opção 2","Opção 3"],delay=1000# delay opcional)response=client.messages.send_poll(instance_id,message,instance_token)
Button Message
fromevolutionapi.models.messageimportButtonMessage,Button# Botão de resposta simplesbuttons= [Button(type="reply",displayText="Opção 1",id="1" ),Button(type="reply",displayText="Opção 2",id="2" )]# Botão com URLbuttons= [Button(type="url",displayText="Visitar Site",url="https://exemplo.com" )]# Botão com número de telefonebuttons= [Button(type="phoneNumber",displayText="Ligar",phoneNumber="5511999999999" )]# Botão com código de cópiabuttons= [Button(type="copyCode",displayText="Copiar Código",copyCode="ABC123" )]message=ButtonMessage(number="5511999999999",title="Título",description="Descrição",footer="Rodapé",buttons=buttons,delay=1000# delay opcional)response=client.messages.send_buttons(instance_id,message,instance_token)
List Message
fromevolutionapi.models.messageimportListMessage,ListSection,ListRowrows= [ListRow(title="Item 1",description="Descrição do item 1",rowId="1" ),ListRow(title="Item 2",description="Descrição do item 2",rowId="2" )]section=ListSection(title="Seção 1",rows=rows)message=ListMessage(number="5511999999999",title="Título da Lista",description="Descrição da lista",buttonText="Clique aqui",footerText="Rodapé",sections=[section],delay=1000# delay opcional)response=client.messages.send_list(instance_id,message,instance_token)
Group Management
Create Group
fromevolutionapi.models.groupimportCreateGroupconfig=CreateGroup(subject="Nome do Grupo",participants=["5511999999999","5511888888888"],description="Descrição do grupo")response=client.group.create_group(instance_id,config,instance_token)
fromevolutionapi.models.groupimportGroupSubjectconfig=GroupSubject(subject="Novo Nome do Grupo")response=client.group.update_group_subject(instance_id,"group_jid",config,instance_token)
Update Group Description
fromevolutionapi.models.groupimportGroupDescriptionconfig=GroupDescription(description="Nova descrição do grupo")response=client.group.update_group_description(instance_id,"group_jid",config,instance_token)
Send Group Invite
fromevolutionapi.models.groupimportGroupInviteconfig=GroupInvite(groupJid="group_jid",description="Convite para o grupo",numbers=["5511999999999","5511888888888"])response=client.group.send_group_invite(instance_id,config,instance_token)
Manage Participants
fromevolutionapi.models.groupimportUpdateParticipant# Adicionar participantesconfig=UpdateParticipant(action="add",participants=["5511999999999","5511888888888"])# Remover participantesconfig=UpdateParticipant(action="remove",participants=["5511999999999"])# Promover a administradorconfig=UpdateParticipant(action="promote",participants=["5511999999999"])# Rebaixar de administradorconfig=UpdateParticipant(action="demote",participants=["5511999999999"])response=client.group.update_participant(instance_id,"group_jid",config,instance_token)
Update Group Settings
fromevolutionapi.models.groupimportUpdateSetting# Ativar modo anúncioconfig=UpdateSetting(action="announcement")# Desativar modo anúncioconfig=UpdateSetting(action="not_announcement")# Bloquear grupoconfig=UpdateSetting(action="locked")# Desbloquear grupoconfig=UpdateSetting(action="unlocked")response=client.group.update_setting(instance_id,"group_jid",config,instance_token)
Toggle Ephemeral Messages
fromevolutionapi.models.groupimportToggleEphemeralconfig=ToggleEphemeral(expiration=86400# 24 horas em segundos)response=client.group.toggle_ephemeral(instance_id,"group_jid",config,instance_token)
fromevolutionapi.models.profileimportPrivacySettingsconfig=PrivacySettings(readreceipts="all",# "all" ou "none"profile="contacts",# "all", "contacts", "contact_blacklist" ou "none"status="contacts",# "all", "contacts", "contact_blacklist" ou "none"online="all",# "all" ou "match_last_seen"last="contacts",# "all", "contacts", "contact_blacklist" ou "none"groupadd="contacts"# "all", "contacts" ou "contact_blacklist")response=client.profile.update_privacy_settings(instance_id,config,instance_token)
fromevolutionapi.models.chatimportPresenceconfig=Presence(number="5511999999999",delay=1000,# delay em mspresence="composing"# "composing", "recording", "paused")response=client.chat.set_presence(instance_id,config,instance_token)
Calls
Simulate Call
fromevolutionapi.models.callimportFakeCall# Chamada de vozconfig=FakeCall(number="5511999999999",isVideo=False,callDuration=30# duração em segundos)# Chamada de vídeoconfig=FakeCall(number="5511999999999",isVideo=True,callDuration=30# duração em segundos)response=client.calls.fake_call(instance_id,config,instance_token)
The Evolution API client supports WebSocket connection to receive real-time events. Here's a guide on how to use it:
Prerequisites
Before using WebSocket, you need to:
Enable WebSocket in your Evolution API by setting the environment variable:
WEBSOCKET_ENABLED=true
Configure WebSocket events for your instance using the WebSocket service:
fromevolutionapi.models.websocketimportWebSocketConfig# Configure WebSocket eventsconfig=WebSocketConfig(enabled=True,events=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS" ])# Set WebSocket configurationresponse=client.websocket.set_websocket(instance_id,config,instance_token)# Get current WebSocket configurationwebsocket_info=client.websocket.find_websocket(instance_id,instance_token)print(f"WebSocket enabled:{websocket_info.enabled}")print(f"Configured events:{websocket_info.events}")
Basic Configuration
There are two ways to create a WebSocket manager:
Using the client's helper method (recommended):
# Create WebSocket manager using the clientwebsocket=client.create_websocket(instance_id="test",api_token="your_api_token",max_retries=5,# Maximum number of reconnection attemptsretry_delay=1.0# Initial delay between attempts in seconds)
application.startup: Triggered when the application starts
instance.create: Triggered when a new instance is created
instance.delete: Triggered when an instance is deleted
remove.instance: Triggered when an instance is removed
logout.instance: Triggered when an instance logs out
Connection and QR Code Events
qrcode.updated: Triggered when the QR Code is updated
connection.update: Triggered when connection status changes
status.instance: Triggered when instance status changes
creds.update: Triggered when credentials are updated
Message Events
messages.set: Triggered when messages are set
messages.upsert: Triggered when new messages are received
messages.edited: Triggered when messages are edited
messages.update: Triggered when messages are updated
messages.delete: Triggered when messages are deleted
send.message: Triggered when a message is sent
messaging-history.set: Triggered when messaging history is set
Contact Events
contacts.set: Triggered when contacts are set
contacts.upsert: Triggered when new contacts are added
contacts.update: Triggered when contacts are updated
Chat Events
chats.set: Triggered when chats are set
chats.update: Triggered when chats are updated
chats.upsert: Triggered when new chats are added
chats.delete: Triggered when chats are deleted
Group Events
groups.upsert: Triggered when groups are created/updated
groups.update: Triggered when groups are updated
group-participants.update: Triggered when group participants are updated
Presence Events
presence.update: Triggered when presence status is updated
Call Events
call: Triggered when there's a call
Typebot Events
typebot.start: Triggered when a typebot starts
typebot.change-status: Triggered when typebot status changes
Label Events
labels.edit: Triggered when labels are edited
labels.association: Triggered when labels are associated/disassociated
Example with Specific Events
defhandle_messages(data):logger.info(f"New message:{data}")defhandle_contacts(data):logger.info(f"Contacts updated:{data}")defhandle_groups(data):logger.info(f"Groups updated:{data}")defhandle_presence(data):logger.info(f"Presence status:{data}")# Registering handlers for different eventswebsocket.on("messages.upsert",handle_messages)websocket.on("contacts.upsert",handle_contacts)websocket.on("groups.upsert",handle_groups)websocket.on("presence.update",handle_presence)
Complete Example
fromevolutionapi.clientimportEvolutionClientfromevolutionapi.models.websocketimportWebSocketConfigimportloggingimporttime# Logging configurationlogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')logger=logging.getLogger(__name__)defhandle_message(data):logger.info(f"New message received:{data}")defhandle_qrcode(data):logger.info(f"QR Code updated:{data}")defhandle_connection(data):logger.info(f"Connection status:{data}")defmain():# Initialize clientclient=EvolutionClient(base_url="http://localhost:8081",api_token="your-api-token" )# Configure WebSocketwebsocket_config=WebSocketConfig(enabled=True,events=["MESSAGES_UPSERT","QRCODE_UPDATED","CONNECTION_UPDATE" ] )# Set WebSocket configurationclient.websocket.set_websocket("instance_id",websocket_config,"instance_token")# Create WebSocket managerwebsocket=client.create_websocket(instance_id="instance_id",api_token="your_api_token",max_retries=5,retry_delay=1.0 )# Register handlerswebsocket.on("messages.upsert",handle_message)websocket.on("qrcode.updated",handle_qrcode)websocket.on("connection.update",handle_connection)try:# Connect to WebSocketwebsocket.connect()logger.info("Connected to WebSocket. Waiting for events...")# Keep the program runningwhileTrue:time.sleep(1)exceptKeyboardInterrupt:logger.info("Closing connection...")websocket.disconnect()exceptExceptionase:logger.error(f"Error:{e}")websocket.disconnect()if__name__=="__main__":main()
Additional Features
Automatic Reconnection
The WebSocket Manager has automatic reconnection with exponential backoff:
websocket=client.create_websocket(instance_id="test",api_token="your_api_token",max_retries=5,# Maximum number of reconnection attemptsretry_delay=1.0# Initial delay between attempts in seconds)
Logging
The WebSocket Manager uses Python's logging system. You can adjust the log level as needed:
# For more detailslogging.getLogger("evolutionapi.services.websocket").setLevel(logging.DEBUG)
Error Handling
The WebSocket Manager has robust error handling:
Automatic reconnection on disconnection
Detailed error logs
Invalid event handling
Data validation
Usage Tips
Always use try/except when connecting to WebSocket
Implement handlers for all events you need to monitor
Use logging for debugging and monitoring
Consider implementing a heartbeat mechanism if needed
Keep your API token secure and don't expose it in logs
Keep your API token secure and don't expose it in logs