kotonebot 0.1.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.
Files changed (70) hide show
  1. kotonebot/__init__.py +40 -0
  2. kotonebot/backend/__init__.py +0 -0
  3. kotonebot/backend/bot.py +302 -0
  4. kotonebot/backend/color.py +525 -0
  5. kotonebot/backend/context/__init__.py +3 -0
  6. kotonebot/backend/context/context.py +1001 -0
  7. kotonebot/backend/context/task_action.py +176 -0
  8. kotonebot/backend/core.py +126 -0
  9. kotonebot/backend/debug/__init__.py +1 -0
  10. kotonebot/backend/debug/entry.py +89 -0
  11. kotonebot/backend/debug/mock.py +79 -0
  12. kotonebot/backend/debug/server.py +223 -0
  13. kotonebot/backend/debug/vars.py +346 -0
  14. kotonebot/backend/dispatch.py +228 -0
  15. kotonebot/backend/flow_controller.py +197 -0
  16. kotonebot/backend/image.py +748 -0
  17. kotonebot/backend/loop.py +277 -0
  18. kotonebot/backend/ocr.py +511 -0
  19. kotonebot/backend/preprocessor.py +103 -0
  20. kotonebot/client/__init__.py +10 -0
  21. kotonebot/client/device.py +500 -0
  22. kotonebot/client/fast_screenshot.py +378 -0
  23. kotonebot/client/host/__init__.py +12 -0
  24. kotonebot/client/host/adb_common.py +94 -0
  25. kotonebot/client/host/custom.py +114 -0
  26. kotonebot/client/host/leidian_host.py +202 -0
  27. kotonebot/client/host/mumu12_host.py +245 -0
  28. kotonebot/client/host/protocol.py +213 -0
  29. kotonebot/client/host/windows_common.py +55 -0
  30. kotonebot/client/implements/__init__.py +7 -0
  31. kotonebot/client/implements/adb.py +85 -0
  32. kotonebot/client/implements/adb_raw.py +159 -0
  33. kotonebot/client/implements/nemu_ipc/__init__.py +8 -0
  34. kotonebot/client/implements/nemu_ipc/external_renderer_ipc.py +280 -0
  35. kotonebot/client/implements/nemu_ipc/nemu_ipc.py +327 -0
  36. kotonebot/client/implements/remote_windows.py +193 -0
  37. kotonebot/client/implements/uiautomator2.py +82 -0
  38. kotonebot/client/implements/windows.py +168 -0
  39. kotonebot/client/protocol.py +69 -0
  40. kotonebot/client/registration.py +24 -0
  41. kotonebot/config/__init__.py +1 -0
  42. kotonebot/config/base_config.py +96 -0
  43. kotonebot/config/manager.py +36 -0
  44. kotonebot/errors.py +72 -0
  45. kotonebot/interop/win/__init__.py +0 -0
  46. kotonebot/interop/win/message_box.py +314 -0
  47. kotonebot/interop/win/reg.py +37 -0
  48. kotonebot/interop/win/shortcut.py +43 -0
  49. kotonebot/interop/win/task_dialog.py +469 -0
  50. kotonebot/logging/__init__.py +2 -0
  51. kotonebot/logging/log.py +18 -0
  52. kotonebot/primitives/__init__.py +17 -0
  53. kotonebot/primitives/geometry.py +290 -0
  54. kotonebot/primitives/visual.py +63 -0
  55. kotonebot/tools/__init__.py +0 -0
  56. kotonebot/tools/mirror.py +354 -0
  57. kotonebot/ui/__init__.py +0 -0
  58. kotonebot/ui/file_host/sensio.py +36 -0
  59. kotonebot/ui/file_host/tmp_send.py +54 -0
  60. kotonebot/ui/pushkit/__init__.py +3 -0
  61. kotonebot/ui/pushkit/image_host.py +87 -0
  62. kotonebot/ui/pushkit/protocol.py +13 -0
  63. kotonebot/ui/pushkit/wxpusher.py +53 -0
  64. kotonebot/ui/user.py +144 -0
  65. kotonebot/util.py +409 -0
  66. kotonebot-0.1.0.dist-info/METADATA +204 -0
  67. kotonebot-0.1.0.dist-info/RECORD +70 -0
  68. kotonebot-0.1.0.dist-info/WHEEL +5 -0
  69. kotonebot-0.1.0.dist-info/licenses/LICENSE +674 -0
  70. kotonebot-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,36 @@
1
+ import requests
2
+ import os
3
+
4
+ def upload(file_path: str) -> str:
5
+ """
6
+ 上传文件到 paste.sensio.no
7
+
8
+ Args:
9
+ file_path: 要上传的文件路径
10
+
11
+ Returns:
12
+ str: 上传后的 URL
13
+ """
14
+ url = 'https://paste.sensio.no/'
15
+ headers = {
16
+ 'accept': 'text/plain',
17
+ 'User-Agent': 'KAA',
18
+ 'x-uuid': ''
19
+ }
20
+
21
+ files = {
22
+ 'file': (os.path.basename(file_path), open(file_path, 'rb'))
23
+ }
24
+
25
+ response = requests.post(url, files=files, headers=headers, allow_redirects=False)
26
+
27
+ if response.status_code != 200:
28
+ raise Exception(f"Upload failed with status code {response.status_code}")
29
+
30
+ return response.text.strip()
31
+
32
+ if __name__ == "__main__":
33
+ test_file = "version"
34
+ if os.path.exists(test_file):
35
+ result = upload(test_file)
36
+ print(f"Upload result: {result}")
@@ -0,0 +1,54 @@
1
+ import requests
2
+ import os
3
+
4
+ def upload(file_path: str) -> str:
5
+ url = 'https://tmpsend.com/upload'
6
+ headers = {
7
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
8
+ 'Referer': 'https://tmpsend.com/',
9
+ }
10
+
11
+ file_name = os.path.basename(file_path)
12
+ file_size = os.path.getsize(file_path)
13
+
14
+ # 第一次请求:添加文件信息
15
+ files = {
16
+ 'action': (None, 'add'),
17
+ 'name': (None, file_name),
18
+ 'size': (None, str(file_size)),
19
+ 'file': (file_name, open(file_path, 'rb'))
20
+ }
21
+
22
+ response = requests.post(url, headers=headers, files=files)
23
+ if response.status_code != 200:
24
+ raise Exception(f"Upload failed with status code {response.status_code}")
25
+
26
+ result = response.json()
27
+ if result.get('hasError'):
28
+ raise Exception(result.get('error'))
29
+
30
+ file_id = result.get('id')
31
+ if not file_id:
32
+ raise Exception("Failed to get file ID")
33
+
34
+ # 第二次请求:上传实际文件
35
+ upload_files = {
36
+ 'action': (None, 'upload'),
37
+ 'id': (None, file_id),
38
+ 'name': (None, file_name),
39
+ 'size': (None, str(file_size)),
40
+ 'start': (None, '0'),
41
+ 'end': (None, str(file_size)),
42
+ 'data': (file_name, open(file_path, 'rb'), 'application/octet-stream')
43
+ }
44
+
45
+ upload_response = requests.post(url, headers=headers, files=upload_files)
46
+ if upload_response.status_code != 200:
47
+ raise Exception(f"File upload failed with status code {upload_response.status_code}")
48
+
49
+ return 'https://tmpsend.com/' + file_id
50
+
51
+ if __name__ == "__main__":
52
+ file_path = r"主题1.thmx"
53
+ print(upload(file_path))
54
+
@@ -0,0 +1,3 @@
1
+ from .protocol import PushkitProtocol
2
+ from .wxpusher import Wxpusher
3
+
@@ -0,0 +1,87 @@
1
+ import os
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Sequence
5
+
6
+ import cv2
7
+ import requests
8
+ import numpy as np
9
+ from cv2.typing import MatLike
10
+ from dotenv import load_dotenv
11
+
12
+ load_dotenv()
13
+
14
+ def _save_temp_image(image: MatLike) -> Path:
15
+ """将OpenCV图片保存为临时文件"""
16
+ temp_file = Path(tempfile.mktemp(suffix='.jpg'))
17
+ cv2.imwrite(str(temp_file), image)
18
+ return temp_file
19
+
20
+ def _upload_single(image: MatLike | str) -> str:
21
+ """
22
+ 上传单张图片到freeimage.host
23
+
24
+ :param image: OpenCV MatLike 或本地图片文件路径
25
+ """
26
+ api_url = 'https://freeimage.host/api/1/upload'
27
+ api_key = os.getenv('FREEIMAGEHOST_KEY')
28
+
29
+ if not api_key:
30
+ raise RuntimeError('Environment variable FREEIMAGEHOST_KEY is not set')
31
+
32
+ # 处理输入
33
+ temp_file = None
34
+ if isinstance(image, str):
35
+ # 本地文件路径
36
+ files = {'source': open(image, 'rb')}
37
+ else:
38
+ # 保存OpenCV图片为临时文件
39
+ temp_file = _save_temp_image(image)
40
+ files = {'source': open(temp_file, 'rb')}
41
+
42
+ data = {
43
+ 'key': api_key,
44
+ 'action': 'upload',
45
+ 'format': 'json'
46
+ }
47
+
48
+ try:
49
+ # 发送POST请求
50
+ response = requests.post(api_url, data=data, files=files)
51
+
52
+ if response.status_code != 200:
53
+ raise RuntimeError(f'Upload failed: HTTP {response.status_code}')
54
+
55
+ result = response.json()
56
+
57
+ if result['status_code'] != 200:
58
+ raise RuntimeError(f'Upload failed: API {result["status_txt"]}')
59
+
60
+ return result['image']['url']
61
+
62
+ finally:
63
+ # 清理临时文件
64
+ files['source'].close()
65
+ if temp_file and temp_file.exists():
66
+ temp_file.unlink()
67
+
68
+ def upload(images: MatLike | str | Sequence[MatLike | str]) -> list[str]:
69
+ """上传一张或多张图片到freeimage.host
70
+
71
+ Args:
72
+ images: 单张图片或图片列表。每个图片可以是OpenCV图片对象或本地图片文件路径
73
+
74
+ Returns:
75
+ 上传后的图片URL列表
76
+ """
77
+ if isinstance(images, (str, np.ndarray)):
78
+ _images = [images]
79
+ elif isinstance(images, Sequence):
80
+ _images = [img for img in images]
81
+ else:
82
+ raise ValueError("Invalid input type")
83
+
84
+ return [_upload_single(img) for img in _images]
85
+
86
+ if __name__ == "__main__":
87
+ print(upload(cv2.imread("res/sprites/jp/common/button_close.png")))
@@ -0,0 +1,13 @@
1
+ from typing import Protocol
2
+
3
+ from cv2.typing import MatLike
4
+
5
+ class PushkitProtocol(Protocol):
6
+ def push(
7
+ self,
8
+ title: str,
9
+ message: str,
10
+ *,
11
+ images: list[str | MatLike] | None = None,
12
+ ) -> None:
13
+ ...
@@ -0,0 +1,53 @@
1
+ import os
2
+ import json
3
+ from typing import Sequence
4
+ import requests
5
+ from cv2.typing import MatLike
6
+ from dotenv import dotenv_values
7
+
8
+ from .image_host import upload
9
+ from .protocol import PushkitProtocol
10
+
11
+ config = dotenv_values(".env")
12
+
13
+ class Wxpusher(PushkitProtocol):
14
+ def __init__(self, app_token: str | None = None, uid: str | None = None):
15
+ self.app_token = app_token or config["WXPUSHER_APP_TOKEN"]
16
+ self.uid = uid or config["WXPUSHER_UID"]
17
+
18
+ def push(self, title: str, message: str, *, images: Sequence[str | MatLike] | None = None) -> None:
19
+ summary = title
20
+ content = message
21
+
22
+ if images:
23
+ image_urls = upload(images)
24
+ img_md = "\n".join([f"![{img_url}]({img_url})" for img_url in image_urls])
25
+ content = content + "\n" + img_md
26
+
27
+ data = {
28
+ "appToken": self.app_token,
29
+ "uid": self.uid,
30
+ "summary": summary,
31
+ "content": content,
32
+ "contentType": 3, # 1: 文本 2: HTML 3: Markdown
33
+ "uids": [self.uid],
34
+ "verifyPay": False,
35
+ "verifyPayType": 0
36
+ }
37
+
38
+ response = requests.post(
39
+ "http://wxpusher.zjiecode.com/api/send/message",
40
+ json=data
41
+ )
42
+ result = response.json()
43
+
44
+ if result["code"] != 1000 or not result["success"]:
45
+ raise RuntimeError(f"推送失败: {result['msg']}")
46
+
47
+ # TODO: 极简推送 https://wxpusher.zjiecode.com/docs/#/?id=spt
48
+
49
+ if __name__ == "__main__":
50
+ import cv2
51
+ wxpusher = Wxpusher()
52
+ wxpusher.push("测试图片", "测试图片", images=[cv2.imread("res/sprites/jp/common/button_close.png")])
53
+
kotonebot/ui/user.py ADDED
@@ -0,0 +1,144 @@
1
+ """消息框、通知、推送等 UI 相关函数"""
2
+ import os
3
+ import time
4
+
5
+ import cv2
6
+ from cv2.typing import MatLike
7
+ from win11toast import toast
8
+
9
+ from .pushkit import Wxpusher
10
+ from .. import logging
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ def retry(func):
15
+ """
16
+ 装饰器:当函数发生 ConnectionResetError 时自动重试三次
17
+ """
18
+ def wrapper(*args, **kwargs):
19
+ for i in range(3):
20
+ try:
21
+ return func(*args, **kwargs)
22
+ except ConnectionResetError:
23
+ if i == 2: # 最后一次重试失败
24
+ raise
25
+ logger.warning(f'ConnectionResetError raised when calling {func}, retrying {i+1}/{3}')
26
+ continue
27
+ return wrapper
28
+
29
+ def _save_local(
30
+ title: str,
31
+ message: str,
32
+ images: list[MatLike] | None = None
33
+ ):
34
+ """
35
+ 保存消息到本地
36
+ """
37
+ if not os.path.exists('messages'):
38
+ os.makedirs('messages')
39
+ file_name = f'messages/{time.strftime("%Y-%m-%d_%H-%M-%S")}'
40
+ with open(file_name + '.txt', 'w', encoding='utf-8') as f:
41
+ logger.verbose('saving message to local: %s', file_name + '.txt')
42
+ f.write(message)
43
+ if images is not None:
44
+ for i, image in enumerate(images):
45
+ logger.verbose('saving image to local: %s', f'{file_name}_{i}.png')
46
+ cv2.imwrite(f'{file_name}_{i}.png', image)
47
+
48
+ @retry
49
+ def push(
50
+ title: str,
51
+ message: str | None = None,
52
+ *,
53
+ images: list[MatLike] | None = None
54
+ ):
55
+ """
56
+ 推送消息
57
+ """
58
+ message = message or ''
59
+ try:
60
+ logger.verbose('pushing to wxpusher: %s', message)
61
+ wxpusher = Wxpusher()
62
+ wxpusher.push(title, message, images=images)
63
+ except Exception as e:
64
+ logger.warning('push remote message failed: %s', e)
65
+ _save_local(title, message, images)
66
+
67
+ def _show_toast(title: str, message: str | None = None, buttons: list[str] | None = None):
68
+ """
69
+ 统一的 Toast 通知函数
70
+
71
+ :param title: 通知标题
72
+ :param message: 通知消息内容
73
+ :param buttons: 按钮列表,如果提供则显示带按钮的通知
74
+ """
75
+ try:
76
+ if buttons:
77
+ logger.verbose('showing toast notification with buttons: %s - %s', title, message or '')
78
+ toast(title, message or '', buttons=buttons)
79
+ else:
80
+ # 如果没有 message,只显示 title
81
+ if message:
82
+ logger.verbose('showing toast notification: %s - %s', title, message)
83
+ toast(title, message)
84
+ else:
85
+ logger.verbose('showing toast notification: %s', title)
86
+ toast(title)
87
+ except Exception as e:
88
+ logger.warning('toast notification failed: %s', e)
89
+
90
+ def ask(
91
+ question: str,
92
+ options: list[tuple[str, str]],
93
+ *,
94
+ timeout: float = -1,
95
+ ) -> str:
96
+ """
97
+ 询问用户
98
+ """
99
+ # 将选项转换为按钮列表
100
+ buttons = [option[1] for option in options]
101
+ _show_toast("琴音小助手询问", question, buttons=buttons)
102
+ raise NotImplementedError
103
+
104
+ def info(
105
+ title: str,
106
+ message: str | None = None,
107
+ images: list[MatLike] | None = None,
108
+ *,
109
+ once: bool = False
110
+ ):
111
+ logger.info('user.info: %s', message)
112
+ push('KAA:' + title, message, images=images)
113
+ _show_toast('KAA:' + title, message)
114
+
115
+ def warning(
116
+ title: str,
117
+ message: str | None = None,
118
+ images: list[MatLike] | None = None,
119
+ *,
120
+ once: bool = False
121
+ ):
122
+ """
123
+ 警告信息。
124
+
125
+ :param message: 消息内容
126
+ :param once: 每次运行是否只显示一次。
127
+ """
128
+ logger.warning('user.warning: %s', message)
129
+ push("琴音小助手警告:" + title, message, images=images)
130
+ _show_toast("琴音小助手警告:" + title, message)
131
+
132
+ def error(
133
+ title: str,
134
+ message: str | None = None,
135
+ images: list[MatLike] | None = None,
136
+ *,
137
+ once: bool = False
138
+ ):
139
+ """
140
+ 错误信息。
141
+ """
142
+ logger.error('user.error: %s', message)
143
+ push("琴音小助手错误:" + title, message, images=images)
144
+ _show_toast("琴音小助手错误:" + title, message)