mineflayer-python 0.1.0__tar.gz

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.
@@ -0,0 +1,9 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Drilegems
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: mineflayer-python
3
+ Version: 0.1.0
4
+ Summary: Python wrapper for Mineflayer Minecraft bot library
5
+ Home-page: https://github.com/yourusername/mineflayer-python
6
+ Author: Your Name
7
+ Author-email: your.email@example.com
8
+ Keywords: minecraft,bot,mineflayer,gaming,automation
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.7
11
+ Classifier: Programming Language :: Python :: 3.8
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Topic :: Games/Entertainment
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.7
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: javascript>=0.1.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=6.0; extra == "dev"
24
+ Requires-Dist: black>=21.0; extra == "dev"
25
+ Requires-Dist: flake8>=3.9; extra == "dev"
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: description-content-type
31
+ Dynamic: home-page
32
+ Dynamic: keywords
33
+ Dynamic: license-file
34
+ Dynamic: provides-extra
35
+ Dynamic: requires-dist
36
+ Dynamic: requires-python
37
+ Dynamic: summary
38
+
39
+ # Mineflayer-Python
40
+
41
+ Python обертка для [Mineflayer](https://github.com/PrismarineJS/mineflayer) - библиотеки для создания Minecraft ботов.
42
+
43
+ ## Установка
44
+
45
+ ```bash
46
+ # Установите Node.js и npm
47
+ # Затем установите mineflayer
48
+ npm install mineflayer
49
+
50
+ # Установите Python пакет
51
+ pip install mineflayer-python
@@ -0,0 +1,13 @@
1
+ # Mineflayer-Python
2
+
3
+ Python обертка для [Mineflayer](https://github.com/PrismarineJS/mineflayer) - библиотеки для создания Minecraft ботов.
4
+
5
+ ## Установка
6
+
7
+ ```bash
8
+ # Установите Node.js и npm
9
+ # Затем установите mineflayer
10
+ npm install mineflayer
11
+
12
+ # Установите Python пакет
13
+ pip install mineflayer-python
@@ -0,0 +1,24 @@
1
+ """
2
+ Mineflayer-Python - Python обертка для Mineflayer
3
+
4
+ Позволяет легко создавать Minecraft ботов с чистым Python API.
5
+ """
6
+
7
+ from .mineflayer import Mineflayer
8
+ from .enums import AuthMode, ViewDistance, Difficulty
9
+ from .enums import OFFLINE, ONLINE, MICROSOFT
10
+
11
+ __version__ = "0.1.0"
12
+ __author__ = "Your Name"
13
+ __all__ = [
14
+ 'Mineflayer',
15
+ 'AuthMode',
16
+ 'ViewDistance',
17
+ 'Difficulty',
18
+ 'OFFLINE',
19
+ 'ONLINE',
20
+ 'MICROSOFT',
21
+ ]
22
+
23
+ # Создаем глобальный экземпляр для удобства
24
+ mineflayer = Mineflayer()
@@ -0,0 +1,178 @@
1
+ import asyncio
2
+ from typing import Any, Dict, Optional, Callable
3
+ from dataclasses import dataclass, field
4
+ from .enums import AuthMode
5
+
6
+ @dataclass
7
+ class BotOptions:
8
+ """Опции для создания бота"""
9
+ host: str = "localhost"
10
+ port: int = 25565
11
+ username: str = "Bot"
12
+ auth: AuthMode = AuthMode.OFFLINE
13
+ version: str = "1.20.1"
14
+ view_distance: int = 8
15
+ chat_length_limit: int = 256
16
+ colors_enabled: bool = True
17
+ default_chat_patterns: bool = True
18
+ physics_enabled: bool = True
19
+ log_errors: bool = True
20
+
21
+ # Дополнительные параметры
22
+ password: Optional[str] = None
23
+ profiles_folder: Optional[str] = None
24
+ client_token: Optional[str] = None
25
+ access_token: Optional[str] = None
26
+ session: Optional[Any] = None
27
+ keep_alive: bool = True
28
+
29
+ def to_dict(self) -> Dict[str, Any]:
30
+ """Конвертирует опции в словарь для JavaScript"""
31
+ result = {
32
+ 'host': self.host,
33
+ 'port': self.port,
34
+ 'username': self.username,
35
+ 'auth': str(self.auth),
36
+ 'version': self.version,
37
+ 'viewDistance': self.view_distance,
38
+ 'chatLengthLimit': self.chat_length_limit,
39
+ 'colorsEnabled': self.colors_enabled,
40
+ 'defaultChatPatterns': self.default_chat_patterns,
41
+ 'physicsEnabled': self.physics_enabled,
42
+ 'logErrors': self.log_errors,
43
+ }
44
+
45
+ # Добавляем опциональные поля
46
+ if self.password:
47
+ result['password'] = self.password
48
+ if self.profiles_folder:
49
+ result['profilesFolder'] = self.profiles_folder
50
+ if self.client_token:
51
+ result['clientToken'] = self.client_token
52
+ if self.access_token:
53
+ result['accessToken'] = self.access_token
54
+ if self.session:
55
+ result['session'] = self.session
56
+ result['keepAlive'] = self.keep_alive
57
+
58
+ return result
59
+
60
+
61
+ class Bot:
62
+ """Представляет Minecraft бота"""
63
+
64
+ def __init__(self, js_bot=None):
65
+ """
66
+ Инициализирует бота
67
+
68
+ Args:
69
+ js_bot: JavaScript объект бота (необязательно)
70
+ """
71
+ self._js_bot = js_bot
72
+ self._event_handlers = {}
73
+
74
+ def __getattr__(self, name):
75
+ """Проксирует вызовы к JavaScript объекту"""
76
+ if self._js_bot:
77
+ return getattr(self._js_bot, name)
78
+ raise AttributeError(f"Bot has no attribute '{name}'")
79
+
80
+ def on(self, event_name: str, callback: Callable):
81
+ """
82
+ Регистрирует обработчик события
83
+
84
+ Args:
85
+ event_name: Название события
86
+ callback: Функция-обработчик
87
+ """
88
+ if event_name not in self._event_handlers:
89
+ self._event_handlers[event_name] = []
90
+ self._event_handlers[event_name].append(callback)
91
+
92
+ # Если бот уже создан, регистрируем обработчик в JavaScript
93
+ if self._js_bot:
94
+ def js_handler(*args):
95
+ try:
96
+ callback(*args)
97
+ except Exception as e:
98
+ print(f"Error in event handler for {event_name}: {e}")
99
+ self._js_bot.on(event_name, js_handler)
100
+
101
+ def once(self, event_name: str, callback: Callable):
102
+ """Регистрирует одноразовый обработчик события"""
103
+ def wrapper(*args):
104
+ callback(*args)
105
+ self.remove_listener(event_name, wrapper)
106
+ self.on(event_name, wrapper)
107
+
108
+ def remove_listener(self, event_name: str, callback: Callable):
109
+ """Удаляет обработчик события"""
110
+ if event_name in self._event_handlers:
111
+ self._event_handlers[event_name].remove(callback)
112
+
113
+ def emit(self, event_name: str, *args):
114
+ """Вызывает событие"""
115
+ if event_name in self._event_handlers:
116
+ for handler in self._event_handlers[event_name]:
117
+ try:
118
+ handler(*args)
119
+ except Exception as e:
120
+ print(f"Error in event handler for {event_name}: {e}")
121
+
122
+ async def wait_for_event(self, event_name: str, timeout: Optional[float] = None):
123
+ """
124
+ Асинхронно ожидает событие
125
+
126
+ Args:
127
+ event_name: Название события
128
+ timeout: Таймаут в секундах
129
+
130
+ Returns:
131
+ Аргументы события
132
+ """
133
+ future = asyncio.Future()
134
+
135
+ def handler(*args):
136
+ if not future.done():
137
+ future.set_result(args)
138
+
139
+ self.once(event_name, handler)
140
+
141
+ try:
142
+ return await asyncio.wait_for(future, timeout)
143
+ except asyncio.TimeoutError:
144
+ self.remove_listener(event_name, handler)
145
+ raise
146
+
147
+ # Удобные методы
148
+ def chat(self, message: str):
149
+ """Отправляет сообщение в чат"""
150
+ if self._js_bot:
151
+ self._js_bot.chat(message)
152
+
153
+ def whisper(self, username: str, message: str):
154
+ """Шепчет игроку"""
155
+ self.chat(f"/tell {username} {message}")
156
+
157
+ def say(self, message: str):
158
+ """Алиас для chat"""
159
+ self.chat(message)
160
+
161
+ def quit(self, reason: str = "Quit"):
162
+ """Отключает бота"""
163
+ if self._js_bot:
164
+ self._js_bot.quit(reason)
165
+
166
+ @property
167
+ def username(self) -> Optional[str]:
168
+ """Возвращает имя бота"""
169
+ if self._js_bot:
170
+ return self._js_bot.username
171
+ return None
172
+
173
+ @property
174
+ def health(self) -> Optional[float]:
175
+ """Возвращает здоровье бота"""
176
+ if self._js_bot and hasattr(self._js_bot, 'health'):
177
+ return float(self._js_bot.health)
178
+ return None
@@ -0,0 +1,25 @@
1
+ """
2
+ Constants for authentication and modes
3
+ """
4
+
5
+ # Authentication modes
6
+ OFFLINE = 'offline'
7
+ ONLINE = 'online'
8
+ MICROSOFT = 'microsoft'
9
+ MOJANG = 'mojang'
10
+
11
+ # Event constants
12
+ EVENT_CHAT = 'chat'
13
+ EVENT_KICKED = 'kicked'
14
+ EVENT_ERROR = 'error'
15
+ EVENT_LOGIN = 'login'
16
+ EVENT_SPAWN = 'spawn'
17
+ EVENT_END = 'end'
18
+ EVENT_DEATH = 'death'
19
+ EVENT_WHISPER = 'whisper'
20
+ EVENT_MESSAGE = 'message'
21
+
22
+ # Other constants
23
+ DEFAULT_PORT = 25565
24
+ DEFAULT_HOST = 'localhost'
25
+ DEFAULT_USERNAME = 'Bot'
@@ -0,0 +1,30 @@
1
+ from enum import Enum, auto
2
+
3
+ class AuthMode(Enum):
4
+ """Режимы аутентификации"""
5
+ OFFLINE = "offline"
6
+ ONLINE = "online"
7
+ MICROSOFT = "microsoft"
8
+
9
+ def __str__(self):
10
+ return self.value
11
+
12
+ class ViewDistance(Enum):
13
+ """Дальность прорисовки"""
14
+ TINY = 2
15
+ SHORT = 4
16
+ NORMAL = 8
17
+ FAR = 16
18
+ EXTREME = 32
19
+
20
+ class Difficulty(Enum):
21
+ """Сложность мира"""
22
+ PEACEFUL = 0
23
+ EASY = 1
24
+ NORMAL = 2
25
+ HARD = 3
26
+
27
+ # Константы для удобства
28
+ OFFLINE = AuthMode.OFFLINE
29
+ ONLINE = AuthMode.ONLINE
30
+ MICROSOFT = AuthMode.MICROSOFT
File without changes
@@ -0,0 +1,171 @@
1
+ import sys
2
+ from typing import Union, Optional, Dict, Any
3
+ from dataclasses import asdict
4
+
5
+ # Проверяем наличие javascript модуля
6
+ try:
7
+ from javascript import require, On, Once, Off, EventEmitter, globalThis
8
+ JS_AVAILABLE = True
9
+ except ImportError:
10
+ JS_AVAILABLE = False
11
+ print("Внимание: модуль 'javascript' не найден. Установите его: pip install javascript")
12
+ print("Эта библиотека требует Node.js и установленного mineflayer через npm")
13
+
14
+ from .bot import Bot, BotOptions
15
+ from .enums import AuthMode, OFFLINE, ONLINE, MICROSOFT
16
+
17
+
18
+ class Mineflayer:
19
+ """Основной класс для работы с Mineflayer"""
20
+
21
+ def __init__(self):
22
+ """
23
+ Инициализирует Mineflayer
24
+
25
+ Raises:
26
+ RuntimeError: Если JavaScript модуль недоступен
27
+ """
28
+ if not JS_AVAILABLE:
29
+ raise RuntimeError(
30
+ "JavaScript модуль недоступен. "
31
+ "Установите: pip install javascript и убедитесь что Node.js установлен"
32
+ )
33
+
34
+ try:
35
+ self._mineflayer_js = require('mineflayer')
36
+ except Exception as e:
37
+ raise RuntimeError(f"Не удалось загрузить mineflayer: {e}. "
38
+ f"Убедитесь что mineflayer установлен: npm install mineflayer")
39
+
40
+ def createBot(self, *args, **kwargs) -> Bot:
41
+ """
42
+ Создает нового бота
43
+
44
+ Args:
45
+ *args: Позиционные аргументы в порядке: host, username, auth, version
46
+ **kwargs: Именованные аргументы
47
+
48
+ Returns:
49
+ Экземпляр Bot
50
+
51
+ Примеры:
52
+ # Позиционные аргументы
53
+ bot = mineflayer.createBot("localhost", "Bot", OFFLINE, "1.16.5")
54
+
55
+ # Именованные аргументы
56
+ bot = mineflayer.createBot(
57
+ host="localhost",
58
+ username="Bot",
59
+ auth=OFFLINE,
60
+ version="1.16.5"
61
+ )
62
+
63
+ # Словарь опций
64
+ bot = mineflayer.createBot({
65
+ "host": "localhost",
66
+ "username": "MyBot"
67
+ })
68
+ """
69
+ # Обработка разных форматов ввода
70
+ if args and len(args) == 1 and isinstance(args[0], dict):
71
+ # Если передан словарь
72
+ options_dict = args[0]
73
+ elif args:
74
+ # Если переданы позиционные аргументы
75
+ options_dict = {}
76
+ if len(args) >= 1:
77
+ options_dict['host'] = args[0]
78
+ if len(args) >= 2:
79
+ options_dict['username'] = args[1]
80
+ if len(args) >= 3:
81
+ options_dict['auth'] = args[2]
82
+ if len(args) >= 4:
83
+ options_dict['version'] = args[3]
84
+ else:
85
+ # Если переданы только именованные аргументы
86
+ options_dict = kwargs
87
+
88
+ # Создаем объект опций
89
+ options = BotOptions(**options_dict)
90
+
91
+ # Создаем JavaScript бота
92
+ js_bot = self._mineflayer_js.createBot(options.to_dict())
93
+
94
+ # Создаем Python обертку
95
+ bot = Bot(js_bot)
96
+
97
+ # Регистрируем обработчики событий
98
+ self._setup_event_proxies(bot, js_bot)
99
+
100
+ return bot
101
+
102
+ def _setup_event_proxies(self, py_bot: Bot, js_bot):
103
+ """Настраивает проксирование событий из JavaScript в Python"""
104
+
105
+ # Список стандартных событий mineflayer
106
+ common_events = [
107
+ 'spawn', 'death', 'health', 'chat', 'whisper', 'actionBar',
108
+ 'login', 'kicked', 'end', 'error', 'playerJoined',
109
+ 'playerLeft', 'entitySpawn', 'entityGone', 'entityMoved',
110
+ 'entityHurt', 'entitySwingArm', 'entityCrouch', 'entityUncrouch',
111
+ 'entityEquip', 'entitySleep', 'entityWake', 'entityEat',
112
+ 'entityAttach', 'entityDetach', 'entityUpdate', 'entityEffect',
113
+ 'entityEffectEnd', 'playerCollect', 'blockUpdate',
114
+ 'chunkColumnLoad', 'chunkColumnUnload', 'soundEffectHeard',
115
+ 'hardcodedSoundEffectHeard', 'noteHeard', 'pistonMove',
116
+ 'rain', 'time', 'scoreboardCreated', 'scoreboardDeleted',
117
+ 'scoreboardTitleChanged', 'scoreUpdated', 'teamCreated',
118
+ 'teamRemoved', 'teamUpdated', 'teamMemberAdded',
119
+ 'teamMemberRemoved', 'resourcePack', 'game'
120
+ ]
121
+
122
+ # Регистрируем обработчики для стандартных событий
123
+ for event in common_events:
124
+ def create_handler(event_name):
125
+ def handler(*args):
126
+ py_bot.emit(event_name, *args)
127
+ return handler
128
+
129
+ js_bot.on(event, create_handler(event))
130
+
131
+ @staticmethod
132
+ def supportedVersions() -> list:
133
+ """Возвращает список поддерживаемых версий"""
134
+ try:
135
+ mineflayer_js = require('mineflayer')
136
+ if hasattr(mineflayer_js, 'supportedVersions'):
137
+ return list(mineflayer_js.supportedVersions)
138
+ except:
139
+ pass
140
+ return ["1.8", "1.9", "1.10", "1.11", "1.12", "1.13", "1.14",
141
+ "1.15", "1.16", "1.17", "1.18", "1.19", "1.20"]
142
+
143
+ def createBotSync(self, *args, **kwargs) -> Bot:
144
+ """
145
+ Создает бота синхронно (для скриптов без asyncio)
146
+
147
+ Returns:
148
+ Экземпляр Bot
149
+ """
150
+ import time
151
+
152
+ bot = self.createBot(*args, **kwargs)
153
+
154
+ # Ждем события spawn с таймаутом
155
+ spawn_event = None
156
+ timeout = 30 # 30 секунд
157
+
158
+ def on_spawn(*args):
159
+ nonlocal spawn_event
160
+ spawn_event = args
161
+
162
+ bot.once('spawn', on_spawn)
163
+
164
+ start_time = time.time()
165
+ while not spawn_event and (time.time() - start_time) < timeout:
166
+ time.sleep(0.1)
167
+
168
+ if not spawn_event:
169
+ raise TimeoutError("Бот не заспавнился в течение 30 секунд")
170
+
171
+ return bot
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: mineflayer-python
3
+ Version: 0.1.0
4
+ Summary: Python wrapper for Mineflayer Minecraft bot library
5
+ Home-page: https://github.com/yourusername/mineflayer-python
6
+ Author: Your Name
7
+ Author-email: your.email@example.com
8
+ Keywords: minecraft,bot,mineflayer,gaming,automation
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.7
11
+ Classifier: Programming Language :: Python :: 3.8
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Topic :: Games/Entertainment
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.7
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: javascript>=0.1.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=6.0; extra == "dev"
24
+ Requires-Dist: black>=21.0; extra == "dev"
25
+ Requires-Dist: flake8>=3.9; extra == "dev"
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: description-content-type
31
+ Dynamic: home-page
32
+ Dynamic: keywords
33
+ Dynamic: license-file
34
+ Dynamic: provides-extra
35
+ Dynamic: requires-dist
36
+ Dynamic: requires-python
37
+ Dynamic: summary
38
+
39
+ # Mineflayer-Python
40
+
41
+ Python обертка для [Mineflayer](https://github.com/PrismarineJS/mineflayer) - библиотеки для создания Minecraft ботов.
42
+
43
+ ## Установка
44
+
45
+ ```bash
46
+ # Установите Node.js и npm
47
+ # Затем установите mineflayer
48
+ npm install mineflayer
49
+
50
+ # Установите Python пакет
51
+ pip install mineflayer-python
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ mineflayer-python/__init__.py
5
+ mineflayer-python/bot.py
6
+ mineflayer-python/constants.py
7
+ mineflayer-python/enums.py
8
+ mineflayer-python/events.py
9
+ mineflayer-python/mineflayer.py
10
+ mineflayer_python.egg-info/PKG-INFO
11
+ mineflayer_python.egg-info/SOURCES.txt
12
+ mineflayer_python.egg-info/dependency_links.txt
13
+ mineflayer_python.egg-info/requires.txt
14
+ mineflayer_python.egg-info/top_level.txt
@@ -0,0 +1,6 @@
1
+ javascript>=0.1.0
2
+
3
+ [dev]
4
+ pytest>=6.0
5
+ black>=21.0
6
+ flake8>=3.9
@@ -0,0 +1 @@
1
+ mineflayer-python
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,39 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ with open("README.md", "r", encoding="utf-8") as fh:
4
+ long_description = fh.read()
5
+
6
+ setup(
7
+ name="mineflayer-python",
8
+ version="0.1.0",
9
+ author="Your Name",
10
+ author_email="your.email@example.com",
11
+ description="Python wrapper for Mineflayer Minecraft bot library",
12
+ long_description=long_description,
13
+ long_description_content_type="text/markdown",
14
+ url="https://github.com/yourusername/mineflayer-python",
15
+ packages=find_packages(),
16
+ classifiers=[
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.7",
19
+ "Programming Language :: Python :: 3.8",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Operating System :: OS Independent",
24
+ "Topic :: Games/Entertainment",
25
+ "Topic :: Software Development :: Libraries",
26
+ ],
27
+ python_requires=">=3.7",
28
+ install_requires=[
29
+ "javascript>=0.1.0",
30
+ ],
31
+ extras_require={
32
+ "dev": [
33
+ "pytest>=6.0",
34
+ "black>=21.0",
35
+ "flake8>=3.9",
36
+ ],
37
+ },
38
+ keywords="minecraft, bot, mineflayer, gaming, automation",
39
+ )