talkerr-api 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
talkerr.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
|
|
2
|
+
import json
|
|
3
|
+
import requests
|
|
4
|
+
import asyncio
|
|
5
|
+
import websockets
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
class Client:
|
|
9
|
+
def __init__(self, token, host="localhost:8000"):
|
|
10
|
+
self.token = token
|
|
11
|
+
self.host = host
|
|
12
|
+
self.http_url = f"http://{host}"
|
|
13
|
+
self.ws_url = f"ws://{host}/ws/bot/{token}"
|
|
14
|
+
self.ws = None
|
|
15
|
+
self.on_message_callback = None
|
|
16
|
+
|
|
17
|
+
# --- DECORADOR PARA EVENTOS ---
|
|
18
|
+
def event(self, func):
|
|
19
|
+
if func.__name__ == "on_message":
|
|
20
|
+
self.on_message_callback = func
|
|
21
|
+
return func
|
|
22
|
+
|
|
23
|
+
# --- UPLOAD DE FOTO REAL ---
|
|
24
|
+
def set_avatar(self, caminho_do_arquivo):
|
|
25
|
+
print(f"A enviar a foto '{caminho_do_arquivo}' para o servidor...")
|
|
26
|
+
if not os.path.exists(caminho_do_arquivo):
|
|
27
|
+
print("❌ Erro: Ficheiro não encontrado!")
|
|
28
|
+
return False
|
|
29
|
+
|
|
30
|
+
with open(caminho_do_arquivo, "rb") as f:
|
|
31
|
+
files = {"file": f}
|
|
32
|
+
data = {"token": self.token}
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
resposta = requests.post(f"{self.http_url}/api/bots/upload_avatar", data=data, files=files)
|
|
36
|
+
res_json = resposta.json()
|
|
37
|
+
if res_json.get("sucesso"):
|
|
38
|
+
print("✅ Avatar atualizado com sucesso!")
|
|
39
|
+
return True
|
|
40
|
+
else:
|
|
41
|
+
print(f"❌ Erro do servidor: {res_json.get('erro')}")
|
|
42
|
+
except Exception as e:
|
|
43
|
+
print(f"❌ Falha de ligação à API: {e}")
|
|
44
|
+
return False
|
|
45
|
+
|
|
46
|
+
# --- ENVIAR MENSAGENS ---
|
|
47
|
+
async def send_message(self, destino, texto):
|
|
48
|
+
if self.ws:
|
|
49
|
+
await self.ws.send(json.dumps({
|
|
50
|
+
"tipo": "mensagem",
|
|
51
|
+
"destino": destino,
|
|
52
|
+
"texto": texto
|
|
53
|
+
}))
|
|
54
|
+
|
|
55
|
+
# --- MOTOR DO WEBSOCKET ---
|
|
56
|
+
async def _conectar(self):
|
|
57
|
+
try:
|
|
58
|
+
async with websockets.connect(self.ws_url) as ws:
|
|
59
|
+
self.ws = ws
|
|
60
|
+
print(f"🤖 Bot ligado ao Talkerr com sucesso!")
|
|
61
|
+
|
|
62
|
+
while True:
|
|
63
|
+
msg = await ws.recv()
|
|
64
|
+
dados = json.loads(msg)
|
|
65
|
+
|
|
66
|
+
# Dispara o evento on_message se alguém programou isso
|
|
67
|
+
if dados.get("tipo") == "msg" and self.on_message_callback:
|
|
68
|
+
# Para o bot não responder a ele mesmo e criar um loop infinito
|
|
69
|
+
if dados.get("remetente") != f"bot_{self.token}": # Isto é só uma trava de segurança básica
|
|
70
|
+
await self.on_message_callback(dados)
|
|
71
|
+
|
|
72
|
+
except websockets.exceptions.ConnectionClosedError as e:
|
|
73
|
+
if e.code == 1008:
|
|
74
|
+
print("❌ Erro fatal: Token inválido ou não autorizado!")
|
|
75
|
+
else:
|
|
76
|
+
print("❌ Ligação perdida.")
|
|
77
|
+
|
|
78
|
+
def run(self):
|
|
79
|
+
asyncio.run(self._conectar())
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
talkerr.py,sha256=l24UMPufDVPhWwRF8FZRm6ZLjvKVXkB1NudevzZiC2E,2967
|
|
2
|
+
talkerr_api-1.0.0.dist-info/METADATA,sha256=gZc2GnfT7qdW6-eeWKnzEL4g471-sOIkDo5hMKxit-o,246
|
|
3
|
+
talkerr_api-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
4
|
+
talkerr_api-1.0.0.dist-info/top_level.txt,sha256=P8iIjkihm8AuAxNqdmD6ygHKfPrNxzFmih8v3kFafbM,8
|
|
5
|
+
talkerr_api-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
talkerr
|