-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
227 lines (197 loc) · 8.71 KB
/
__init__.py
File metadata and controls
227 lines (197 loc) · 8.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
__plugin_meta__ = {
"name": "JRPG Bot",
"description": "A JRPG bot for Coral.",
"version": "0.1.2",
"compatibility": "250608"
}
import os
import json
import logging
import sqlite3
import importlib.util
from Coral import register, config, perm_system, on_message, MessageEvent, MessageRequest, MessageChain, MessageSegment
logger = logging.getLogger("jrpgbot")
perm_system.register_perm("jrpgbot", "Base permission for the jrpgbot plugin.")
perm_system.register_perm("jrpgbot.control", "Permission to control the jrpgbot plugin.")
class JRPGBot:
register = None
config = None
perm_system = None
def __init__(self, register, config, perm_system):
self.register = register
self.config = config
self.perm_system = perm_system
self.jrpg_functions = {}
self.jrpg_events = {}
self.load_db()
self.load_functions()
self.bot_status = False
def load_functions(self):
self.jrpg_functions['bot'] = self.bot_control
self.jrpg_functions['info'] = self.info
for file in os.listdir(os.path.join(os.path.dirname(__file__), "utils")):
if file.endswith(".py") and not file.startswith("__init__"):
spec = importlib.util.spec_from_file_location(file[:-3], os.path.join(os.path.dirname(__file__), "utils", file))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if hasattr(module, "register_function"):
module.register_function(self.jrpg_functions, self.jrpg_events, self.conn)
logger.info(f"Loaded {len(self.jrpg_functions)} jrpg functions.")
async def jrpg_command(self, message: MessageEvent):
raw_message = message.message.to_plain_text()
sender_user_id = message.user.user_id
group_id = message.group.group_id if message.group is not None else -1
if not raw_message.startswith('.'):
return None
logger.info(f"Received jrpg command from {sender_user_id} in {group_id}: {raw_message}")
try:
command = raw_message[1:].split()[0]
args = raw_message[1:].split()[1:]
except IndexError:
return MessageChain([MessageSegment.text("Invalid command format.")])
if not self.bot_status and command not in ["bot", "info"]:
return None
if command not in self.jrpg_functions:
return MessageChain([MessageSegment.text(f"Command {command} not found.")])
try:
result = await self.jrpg_functions[command](args, self.userslot, sender_user_id, group_id)
except Exception as e:
logger.exception(f"Error executing command {command}: {e}")
return MessageChain([MessageSegment.text(f"Error executing command: {e}")])
slot_id = self.userslot.get(sender_user_id)
cursor = self.conn.cursor()
cursor.execute("SELECT name FROM users WHERE user_id =? AND slot_id =?", (sender_user_id, slot_id,))
name_row = cursor.fetchone()
name = name_row[0] if name_row else None
# 构建基础消息链
def build_base_chain(content):
chain_segments = [MessageSegment.at(sender_user_id), MessageSegment.text("\n")]
if name:
chain_segments.append(MessageSegment.text(f"[{name}] "))
chain_segments.append(MessageSegment.text(content))
if group_id == -1:
chain_segments.append(MessageSegment.text("\n警告:你正在私聊模式下使用JRPG Bot,可能无法正常运行。"))
return MessageChain(chain_segments)
# 处理不同类型的结果
if isinstance(result, list):
# 多个消息的情况
messages = []
for i, r in enumerate(result):
if i == 0:
messages.append(build_base_chain(r))
else:
messages.append(MessageChain([MessageSegment.text(r)]))
return messages
elif isinstance(result, str):
# 单个消息的情况
return build_base_chain(result)
else:
# 其他类型直接返回
return result
async def bot_control(self, args, userslot, sender_user_id, group_id):
if not self.perm_system.check_perm(["jrpgbot", "jrpgbot.control"], sender_user_id, group_id):
return "You don't have permission to control the jrpgbot plugin."
if len(args) > 0 and args[0].startswith("on"):
self.bot_status = True
return "JRPG Bot is now on."
elif len(args) > 0 and args[0].startswith("off"):
self.bot_status = False
return "JRPG Bot is now off."
else:
return "Invalid command format. Usage: .bot [on|off]"
def load_db(self):
if not os.path.exists("./data/jrpgbot"):
os.makedirs("./data/jrpgbot")
try:
self.conn = sqlite3.connect("./data/jrpgbot/usertable.db", check_same_thread=False)
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS users
(user_id INTEGER,
slot_id INTEGER,
name TEXT,
str INTEGER,
con INTEGER,
siz INTEGER,
dex INTEGER,
app INTEGER,
int INTEGER,
pow INTEGER,
edu INTEGER,
luk INTEGER,
PRIMARY KEY (user_id, slot_id))''')
self.conn.execute('''
CREATE TABLE IF NOT EXISTS status
(user_id INTEGER,
slot_id INTEGER,
hp INTEGER,
mp INTEGER,
dmg TEXT,
def TEXT,
san INTEGER,
PRIMARY KEY (user_id, slot_id))''')
self.conn.execute('''
CREATE TABLE IF NOT EXISTS skills
(user_id INTEGER,
slot_id INTEGER,
skillname TEXT,
expression TEXT,
PRIMARY KEY (user_id, slot_id, skillname))''')
except sqlite3.Error as e:
raise e
self.userslot = UserSlot("./data/jrpgbot/userslot.json")
logger.info("Loaded database.")
async def info(self, *args, **kwargs):
coral_ver = self.config.get("coral_version")
return f"JRPG Bot v0.1.2, by Akina絵\nRunning on Coral {coral_ver}"
class UserSlot:
slot_path = "./data/jrpgbot/userslot.json"
def __init__(self, slot_path):
self.slot_path = slot_path
if not os.path.exists(self.slot_path):
with open(self.slot_path, "w") as f:
json.dump({}, f, indent=4)
with open(self.slot_path, "r") as f:
self.slot_id = json.load(f)
def get(self, user_id):
user_id = str(user_id)
if user_id not in self.slot_id:
self.slot_id[user_id] = 1
self.save()
return self.slot_id[user_id]
def set(self, user_id, slot_id):
self.slot_id[str(user_id)] = int(slot_id)
self.save()
def save(self):
with open(self.slot_path, "w") as f:
json.dump(self.slot_id, f, indent=4)
jrpgbot_instance = JRPGBot(register, config, perm_system)
@on_message(priority=5)
async def jrpg_command_listener(message: MessageEvent):
result = await jrpgbot_instance.jrpg_command(message)
if result is None:
return None
# 处理不同类型的返回结果
if isinstance(result, list):
# 返回多个MessageRequest
return [
MessageRequest(
platform=message.platform,
event_id=message.event_id,
self_id=message.self_id,
message=msg,
user=message.user,
group=message.group if message.group is not None else None
)
for msg in result
]
else:
# 返回单个MessageRequest
return MessageRequest(
platform=message.platform,
event_id=message.event_id,
self_id=message.self_id,
message=result,
user=message.user,
group=message.group if message.group is not None else None
)