饥荒联机版游戏内消息和QQ群内消息互通

云服务器配置如下:

  • CPU:2核
  • 内存:4GB
  • 带宽:6Mbps
  • 操作系统:Ubuntu 22.04.5 LTS

0 背景介绍

我在玩饥荒(联机版)的时候,时常会在游戏过程中和游戏外的朋友讨论或分享,但是每次发送或查看消息时就要切屏到QQ或微信,有点麻烦,这时候我就想:如果朋友们发的消息能同步到我游戏内的聊天系统里就好了,甚至我直接在游戏内发消息,朋友们就能在QQ或微信里看到。

于是我开始求助于AI,询问相关的技术方案,经过一番尝试和调试,终于实现了这个功能。本文就记录了如何把饥荒联机版游戏内的聊天消息和系统消息实时同步到QQ群中,并把QQ群内成员的所有发言实时同步到游戏内。

起初我是想用微信机器人的,但是经过调研发现,微信机器人的限制较多,不如QQ机器人友好,最终我选择了QQ机器人作为桥接工具。

该方案使用了QQ官方提供的机器人API接口,使用Python编写了一个桥接服务,运行在饥荒服务器所在的机器上。该服务会监听饥荒服务器的聊天日志,并通过QQ机器人API将消息发送到指定的QQ群,同时也会监听QQ群内的消息,并将其发送到饥荒服务器的控制台,从而实现双向消息同步。

因此该方案对饥荒服务器本身的配置没有任何修改,也不会影响游戏的正常运行,只是增加了一个额外的桥接服务来实现消息互通,属于无入侵式的扩展功能。

最后,该方案仅适用于个人使用或小范围的朋友群体,扩展性和健壮性较差,其中的脚本全部由AI生成,但优点是成本低廉、易于实现,适合个人或小团队使用。

1 创建QQ机器人

  • 访问https://q.qq.com/进入QQ开放平台,登录账号并完成实名认证;
  • 找到“QQ机器人开放平台”栏目,进入并创建一个机器人,创建完成后记住AppID和AppSecret,后面要用。

2 配置机器人

  • 下载或更新最新版的手机QQ,把机器人拉到QQ群里
  • 在群内点击QQ机器人的用户名片,在点击名片右上角的设置按钮进入机器人设置页面:
    • 机器人可获取的群聊消息范围设置为获取群内全部消息
    • 机器人主动在群聊内发言的开关打开

3 配置饥荒服务器

该功能不会修改饥荒服务器本身的配置,而是单独运行一个桥接服务来做如下事情:

  • 监听饥荒服务器游戏内的消息,实时推送到机器人所在的群里(通过机器人发言的方式)
  • 通过接收机器人在群里监听到的群成员发言,实时推送到饥荒服务器游戏内(通过饥荒控制台指令的方式)

3.1 安装服务器所需依赖和环境

1
2
sudo apt install -y screen python3 python3-aiohttp
sudo pip3 install websockets

3.2 编写脚本

在编写脚本之前,可以先创建一个工作目录方便管理相关文件。 比如创建~/dst_qq_bridge/目录。

在该目录中新建dst_qq_bridge.py文件,内容如下:

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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import asyncio
import json
import os
import re
import subprocess
import sys
import time
from pathlib import Path
import aiohttp
import websockets

# ==================== 配置加载 ====================
BASE_DIR = Path(__file__).resolve().parent
CONFIG_PATH = BASE_DIR / "config.json"


def load_config() -> dict:
if not CONFIG_PATH.exists():
print(f"[Config] 未找到配置文件,请确认后重新启动服务")
sys.exit(1)

try:
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
cfg = json.load(f)
print("[Config] 配置文件加载成功")
return cfg
except Exception as e:
print(f"[Config] 配置文件解析失败: {e}")
sys.exit(1)


CONFIG = load_config()

# 基础参数
QQ_APP_ID = str(CONFIG["qq_bot"]["app_id"])
QQ_APP_SECRET = str(CONFIG["qq_bot"]["app_secret"])
DST_SCREEN_NAME = CONFIG["dst"]["screen_name"]
DST_LOG_PATH = Path(CONFIG["dst"]["chat_log_path"])
MAX_MSG_LEN = int(CONFIG["dst"].get("max_msg_len", 60))
MAX_AUTHOR_LEN = int(CONFIG["dst"].get("max_author_len", 16))

# 文件路径
_bind_file = Path(CONFIG["storage"].get("group_bind_file", "group_bind.txt"))
CONFIG_FILE = _bind_file if _bind_file.is_absolute() else BASE_DIR / _bind_file

_nicks_file = Path(CONFIG["storage"].get("user_nicks_file", "user_nicks.json"))
NICKS_FILE = _nicks_file if _nicks_file.is_absolute() else BASE_DIR / _nicks_file

# 模板解析与前缀提取
TEMPLATES = CONFIG.get("templates", {})
QQ_ANNOUNCE_PREFIX = TEMPLATES.get("qq_to_game_announce", "").split("{")[0].strip()
GAME_MSG_PREFIX = TEMPLATES.get("game_to_qq_chat", "").split("{")[0].strip()


def render_template(tpl_key: str, **kwargs) -> str:
"""根据模板 key 渲染内容,如果模板为空则返回空字符串(用于禁用该提示)"""
tpl = TEMPLATES.get(tpl_key, "")
if not tpl:
return ""
try:
return tpl.format(**kwargs)
except Exception as e:
print(f"[Template] 模板 {tpl_key} 渲染失败: {e}")
return ""


# 恢复群绑定
initial_group_id = None
if CONFIG_FILE.exists():
try:
initial_group_id = CONFIG_FILE.read_text(encoding="utf-8").strip() or None
if initial_group_id:
print(f"[Bridge] 从持久化文件恢复绑定的群: {initial_group_id}")
except Exception as e:
print(f"[Bridge] 读取群绑定文件失败: {e}")

state = {
"access_token": "",
"token_expires_at": 0,
"group_openid": initial_group_id,
"last_seq": 0,
"user_nicks": {}, # { member_openid: "备注名" }
"nicks_file_mtime": 0, # 记录文件最后修改时间,用于热加载
}


# ==================== 昵称持久化与热加载 ====================
def load_nicks_from_disk(force: bool = False):
"""从磁盘加载昵称映射,支持检测文件修改后自动热更新"""
if not NICKS_FILE.exists():
try:
NICKS_FILE.write_text("{}", encoding="utf-8")
except Exception:
pass
return

try:
current_mtime = NICKS_FILE.stat().st_mtime
if force or current_mtime > state["nicks_file_mtime"]:
content = NICKS_FILE.read_text(encoding="utf-8").strip()
state["user_nicks"] = json.loads(content) if content else {}
state["nicks_file_mtime"] = current_mtime
print(f"[NickManager] 昵称配置已更新/热加载,当前已绑定 {len(state['user_nicks'])} 位成员")
except Exception as e:
print(f"[NickManager] 读取 user_nicks.json 异常: {e}")


def save_nick_to_disk(member_openid: str, nick: str):
"""保存新备注到本地文件"""
load_nicks_from_disk()
state["user_nicks"][member_openid] = nick
try:
NICKS_FILE.write_text(json.dumps(state["user_nicks"], ensure_ascii=False, indent=2), encoding="utf-8")
state["nicks_file_mtime"] = NICKS_FILE.stat().st_mtime
print(f"[NickManager] 成功写入备注: {member_openid} -> {nick}")
except Exception as e:
print(f"[NickManager] 写入 user_nicks.json 失败: {e}")


def resolve_author_nick(event_data: dict) -> str:
"""解析发送者昵称:支持热重载,优先自定义备注"""
load_nicks_from_disk()

author_data = event_data.get("author", {})
member_openid = author_data.get("member_openid") or author_data.get("id", "")

if member_openid in state["user_nicks"]:
return state["user_nicks"][member_openid]

raw_name = author_data.get("username", "").strip()
if raw_name and raw_name != ".":
return raw_name

return f"群友_{member_openid[:4]}"


# ==================== 消息清洗与过滤正则 ====================
QQ_FACE_PATTERN = re.compile(r"\[?<face(?:Type)?\b[^>\r\n]{1,200}?>\]?|\[?<face:\d+>\]?", re.IGNORECASE)
EMOJI_PATTERN = re.compile(
"["
"\U0001F300-\U0001F5FF"
"\U0001F600-\U0001F64F"
"\U0001F680-\U0001F6FF"
"\U0001F900-\U0001F9FF"
"\U0001FA70-\U0001FAFF"
"\U0001F1E6-\U0001F1FF"
"\U00002600-\U000026FF"
"\U00002700-\U000027BF"
"]+",
flags=re.UNICODE
)
URL_PATTERN = re.compile(r"https?://[^\s]+", re.IGNORECASE)


def summarize_qq_message(event_data: dict, app_id: str) -> str:
"""清洗 QQ 消息,格式化特殊实体与附件"""
raw_content = event_data.get("content", "").strip()

clean_text = raw_content.replace(f"<@!{app_id}>", "").strip()
clean_text = QQ_FACE_PATTERN.sub("[表情]", clean_text)
clean_text = EMOJI_PATTERN.sub("[表情]", clean_text)
clean_text = URL_PATTERN.sub("[链接]", clean_text)

attachments = event_data.get("attachments", [])
if attachments:
attach_tags = []
for att in attachments:
content_type = str(att.get("content_type", "")).lower()
if "face" in content_type or "sticker" in content_type:
attach_tags.append("[表情]")
elif "image" in content_type:
attach_tags.append("[图片]")
elif "video" in content_type:
attach_tags.append("[视频]")
elif "audio" in content_type or "voice" in content_type:
attach_tags.append("[语音]")
else:
attach_tags.append("[文件]")

media_str = "".join(attach_tags)
clean_text = f"{clean_text} {media_str}".strip() if clean_text else media_str

clean_text = re.sub(r"\[+表情\]+", "[表情]", clean_text)
clean_text = re.sub(r"\[+图片\]+", "[图片]", clean_text)
clean_text = re.sub(r"(\[表情\]\s*)+", "[表情]", clean_text)
clean_text = re.sub(r"(\[图片\]\s*)+", "[图片]", clean_text)

return clean_text.strip()


# ==================== QQ 官方 API 交互 ====================
async def get_access_token():
now = asyncio.get_event_loop().time()
if state["access_token"] and now < state["token_expires_at"]:
return state["access_token"]

url = "https://bots.qq.com/app/getAppAccessToken"
payload = {"appId": QQ_APP_ID, "clientSecret": QQ_APP_SECRET}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload) as resp:
data = await resp.json()
state["access_token"] = data["access_token"]
state["token_expires_at"] = now + int(data.get("expires_in", 7200)) - 60
return state["access_token"]


async def send_to_qq_group(content: str, reply_msg_id: str = None):
if not content:
return
if not state["group_openid"]:
print("[Bridge] 未捕获到 group_openid,需群内先发送消息激活绑定")
return

token = await get_access_token()
url = f"https://api.sgroup.qq.com/v2/groups/{state['group_openid']}/messages"
headers = {
"Authorization": f"QQBot {token}",
"Content-Type": "application/json"
}
payload = {"content": content, "msg_type": 0}
if reply_msg_id:
payload["msg_id"] = reply_msg_id

async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload, headers=headers) as resp:
if resp.status != 200:
print(f"[Bridge] 推送群消息失败 [{resp.status}]: {await resp.text()}")


def sanitize_dst_text(text: str, max_len: int) -> str:
"""清洗并截断传入饥荒控制台的文本,对 Lua 字符转义"""
if not text:
return ""

cleaned = text.replace("\r\n", " ").replace("\n", " ").replace("\r", " ").replace("\t", " ")
cleaned = "".join(ch for ch in cleaned if ord(ch) >= 32)
cleaned = re.sub(r"\s+", " ", cleaned).strip()

if len(cleaned) > max_len:
cleaned = cleaned[:max_len] + "..."

cleaned = cleaned.replace("\\", "\\\\").replace('"', '\\"')
return cleaned


def announce_to_dst(author: str, text: str):
"""向饥荒主世界控制台注入广播"""
safe_author = sanitize_dst_text(author, max_len=MAX_AUTHOR_LEN)
safe_text = sanitize_dst_text(text, max_len=MAX_MSG_LEN)

if not safe_text:
return

dst_msg = render_template("qq_to_game_announce", author=safe_author, content=safe_text)
if not dst_msg:
return

lua_cmd = f'c_announce("{dst_msg}")\n'
cmd_args = [
"screen",
"-S", DST_SCREEN_NAME,
"-p", "0",
"-X", "stuff",
lua_cmd
]

try:
subprocess.run(cmd_args, check=True)
except Exception as e:
print(f"[Bridge] 注入饥荒控制台异常: {e}")


# ==================== 饥荒日志监听 ====================
async def tail_server_log():
print(f"[LogWatcher] 开始监听饥荒全服聊天日志: {DST_LOG_PATH}")
while not DST_LOG_PATH.exists():
print("[LogWatcher] 等待聊天日志生成...")
await asyncio.sleep(2)

proc = await asyncio.create_subprocess_exec(
"tail", "-n", "0", "-F", str(DST_LOG_PATH),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL
)

say_pattern = re.compile(r"\[Say\]\s*\([^)]*\)\s*([^:]+):\s*(.*)")
join_pattern = re.compile(r"\[Join Announcement\]\s*(.*)")
leave_pattern = re.compile(r"\[Leave Announcement\]\s*(.*)")
death_pattern = re.compile(r"\[Death Announcement\]\s*(.*)")

while True:
line_bytes = await proc.stdout.readline()
if not line_bytes:
await asyncio.sleep(0.5)
continue

line = line_bytes.decode("utf-8", errors="ignore").strip()
if not line:
continue

say_match = say_pattern.search(line)
if say_match:
player = say_match.group(1).strip()
content = say_match.group(2).strip()

# 核心过滤:检测是否包含注入前缀,防止游戏公屏回声重复推送
if QQ_ANNOUNCE_PREFIX and (content.startswith(QQ_ANNOUNCE_PREFIX) or QQ_ANNOUNCE_PREFIX in content):
continue

print(f"[游戏公屏] {player}: {content}")
msg = render_template("game_to_qq_chat", player=player, content=content)
await send_to_qq_group(msg)
continue

join_match = join_pattern.search(line)
if join_match:
player = join_match.group(1).strip()
print(f"[玩家上线] {player}")
msg = render_template("game_to_qq_join", player=player)
await send_to_qq_group(msg)
continue

leave_match = leave_pattern.search(line)
if leave_match:
player = leave_match.group(1).strip()
print(f"[玩家下线] {player}")
msg = render_template("game_to_qq_leave", player=player)
await send_to_qq_group(msg)
continue

death_match = death_pattern.search(line)
if death_match:
death_info = death_match.group(1).strip()
print(f"[玩家阵亡] {death_info}")
msg = render_template("game_to_qq_death", death_info=death_info)
await send_to_qq_group(msg)
continue


# ==================== 网关监听与指令解析 ====================
async def start_qq_gateway():
load_nicks_from_disk(force=True)

while True:
try:
token = await get_access_token()
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.sgroup.qq.com/gateway",
headers={"Authorization": f"QQBot {token}"}
) as resp:
gw_data = await resp.json()
gateway_url = gw_data["url"]

async with websockets.connect(gateway_url) as ws:
identify_payload = {
"op": 2,
"d": {
"token": f"QQBot {token}",
"intents": 1 << 25,
"shard": [0, 1]
}
}
await ws.send(json.dumps(identify_payload))
print("[Gateway] 已连接至 QQ WebSocket 网关 (Intents: 1 << 25)")

async for raw_msg in ws:
msg = json.loads(raw_msg)
op = msg.get("op")
t = msg.get("t")
d = msg.get("d", {})

if op == 10:
heartbeat_interval = d["heartbeat_interval"] / 1000
async def heartbeat():
while True:
await asyncio.sleep(heartbeat_interval)
await ws.send(json.dumps({"op": 1, "d": state["last_seq"]}))
asyncio.create_task(heartbeat())

elif op == 0:
state["last_seq"] = msg.get("s", state["last_seq"])

if t in ["GROUP_AT_MESSAGE_CREATE", "GROUP_MESSAGE_CREATE"]:
print(f"[{CONFIG['qq_bot']['app_id']}] 收到群事件: {t}, msg_id: {d.get('id')}, content: {d.get('content')}")
if d.get("author", {}).get("bot", False):
continue

current_group = d.get("group_openid")
if current_group and current_group != state["group_openid"]:
state["group_openid"] = current_group
try:
CONFIG_FILE.write_text(current_group, encoding="utf-8")
print(f"[Bridge] 自动同步群绑定: {current_group}")
except Exception as e:
print(f"[Bridge] 持久化群文件失败: {e}")

clean_content = summarize_qq_message(d, QQ_APP_ID)
msg_id = d.get("id")

# ---------------- 指令识别: 改名 / 绑定 ----------------
cmd_match = re.match(r"^[#/](改名|绑定|备注|角色|人物)\s+(.+)$", clean_content)
if cmd_match:
action_type = cmd_match.group(1)
new_nick = cmd_match.group(2).strip()
member_openid = d.get("author", {}).get("member_openid") or d.get("author", {}).get("id", "")

if member_openid and new_nick:
save_nick_to_disk(member_openid, new_nick)
label = "角色/身份" if action_type in ["角色", "人物"] else "发言备注"
reply_text = render_template("qq_nick_set_success", label=label, nick=new_nick)
print(f"[NickManager] 用户自主绑定成功: {new_nick} ({member_openid})")
await send_to_qq_group(reply_text, reply_msg_id=msg_id)
continue
# -----------------------------------------------------

# 过滤机器人自己推送至群内的游戏前缀回声
if GAME_MSG_PREFIX and clean_content.startswith(GAME_MSG_PREFIX):
continue

if clean_content:
author_name = resolve_author_nick(d)
print(f"[QQ -> DST] {author_name}: {clean_content}")
announce_to_dst(author_name, clean_content)

except Exception as e:
print(f"[Gateway] 连接异常: {e},5秒后自动重连")
await asyncio.sleep(5)


async def main():
await asyncio.gather(
tail_server_log(),
start_qq_gateway()
)


if __name__ == '__main__':
asyncio.run(main())

3.3 添加配置文件

在工作目录创建config.json文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
"qq_bot": {
"app_id": "1234567890",
"app_secret": "abcdefghijklmnopqrstuvwxyz"
},
"dst": {
"screen_name": "dst_master",
"chat_log_path": "/home/guozhuang/.klei/DoNotStarveTogether/GZOnline/Master/server_chat_log.txt",
"max_msg_len": 60,
"max_author_len": 16
},
"storage": {
"group_bind_file": "group_bind.txt",
"user_nicks_file": "user_nicks.json"
},
"templates": {
"game_to_qq_chat": "[永恒领域] {player}: {content}",
"game_to_qq_join": "[永恒领域] 玩家 {player} 已经加入游戏。",
"game_to_qq_leave": "[永恒领域] 玩家 {player} 断开连接。",
"game_to_qq_death": "[永恒领域] {death_info}",
"qq_to_game_announce": "[绚丽之门另一端] {author}: {content}",
"qq_nick_set_success": "您的游戏内{label}已成功设定为:{nick}"
}
}

说明:

  • qq_bot: QQ机器人相关配置
    • app_id: 机器人ID
    • app_secret: 机器人密钥
  • dst: 饥荒相关配置
    • screen_name: 饥荒服务的screen会话名称
    • chat_log_path: 饥荒Master世界的聊天日志文件
    • max_msg_len: 显示的最大消息长度(字符)
    • max_author_len: 显示的最大用户名称长度(字符)
  • storage: 存储相关配置
    • group_bind_file: 绑定的群ID存储文件路径
    • user_nicks_file: 绑定的用户昵称存储文件路径
  • templates: 消息模板相关配置
    • game_to_qq_chat: 游戏内的聊天消息转发到QQ群里时的消息格式模板
    • game_to_qq_join: 游戏内的加入游戏消息转发到QQ群里时的消息格式模板
    • game_to_qq_leave: 游戏内的离开游戏消息转发到QQ群里时的消息格式模板
    • game_to_qq_death: 游戏内的玩家死亡消息转发到QQ群里时的消息格式模板
    • qq_to_game_announce: QQ群内的消息转发到游戏内时的消息格式模板
    • qq_nick_set_success: QQ群内的用户设置昵称成功后的提示消息模板

3.4 注册成服务并启动

  1. 首先新建dst-bridge.service文件,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[Unit]
Description=DST to QQ Bot Bridge Service
After=network.target

[Service]
Type=simple
# 修改成自己的用户名
User=guozhuang
Group=guozhuang
# 工作目录位置
WorkingDirectory=/home/guozhuang/dst_qq_bridge
Environment=PYTHONUNBUFFERED=1
# 启动命令 注意后面的脚本路径
ExecStart=/usr/bin/python3 -u /home/guozhuang/dst_qq_bridge/dst_qq_bridge.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
  1. 把该文件移动到/ect/systemd/system/目录下
  2. 依次执行sudo systemctl daemon-reload和sudo systemctl start dst-bridge.service命令
  3. 如有需要,可以把该服务设置成开机自启:sudo systemctl enable dst-bridge.service

4 使用说明

4.1 首次使用

首次使用时,需要在群里@机器人发送任意消息即可自动绑定群号,之后机器人就会自动把游戏内的聊天消息和系统消息推送到该群里,并把群成员的发言同步到游戏内且无需手动@机器人。

4.2 群成员设置游戏内昵称

默认情况下,QQ群里如果有成员发言,游戏内显示的成员名称是TA的网名,如果希望在游戏内显示自定义的昵称,可以在群里发送以下任意指令即可把游戏内显示的昵称改为XXX:

  • #改名 XXX
  • #备注 XXX
  • #绑定 XXX
  • #角色 XXX
  • #人物 XXX

修改成功后,机器人会回复相应的提示信息。

4.3 查看桥接服务运行日志

可以通过以下命令查看桥接服务的运行日志:

1
sudo journalctl -u dst-bridge.service -f

5 注意事项

5.1 关于饥荒服务器

该方案中的饥荒服务器使用的screen程序在后台运行,因此对于未使用该程序的饥荒服务器搭建方案并不兼容。

另外,经过测试发现,对于同时开了Master和Caves甚至更多世界分片的服务,需要将不同世界分片分别运行在多个不同的screen会话中,否则程序在向控制台发送c_announce指令时可能会出现异常。

比如把饥荒服务器的启动脚本修改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
cd "$install_dir/bin64" || fail

run_shared=(./dontstarve_dedicated_server_nullrenderer_x64)
run_shared+=(-cluster "$cluster_name")
# run_shared+=(-monitor_parent_process $$)

# 启动Master会话
screen -dmS ${screen_master_session} "${run_shared[@]}" -shard Master

# 启动Caves会话
screen -dmS ${screen_caves_session} "${run_shared[@]}" -shard Caves

echo "[${cluster_name}]Master和Caves已分别在后台screen启动完成(${screen_master_session}/${screen_caves_session})"

5.2 关于该方案

该方案在安全性和健壮性上有很大欠缺,仅用于个人使用,比如不支持消息防注入,所以群成员发言时需要注意不要发送带特殊字符的内容,否则可能会引起程序异常。