跳到正文

科技·工程

QQ Message Fetcher 使用说明

picha约 18 分钟
原文
文章信息与版本

文章信息

发布
2025年10月27日
收录
2025年12月12日
更新
2026年10月27日
篇幅
约 18 分钟

版本

  1. v3当前
  2. v2
  3. v1

这个插件是我拿 AI 乱写一通写出来的,只是一个半成品,可能有各种各样的 bug。

如果在爬取的过程中出锅了,请先重启 bot 再次尝试爬取,可能是 QQ 的 api 出病导致的。

这个插件并不打算大规模投入正式使用,初衷只是为了个人用途爬取并保存 U 群消息,但是群友们表示希望共享出来,于是就写了一个安装说明。

本人不会持续维护,遇到 bug 也不一定会修,神通广大的群友们可以自行随意使用及修改。

本人对使用本插件产生的后果概不负责。

本插件采用 CC0(Creative Commons Zero)协议分发。

由于本插件实质上只有一份 python 代码,故不发 github 仓库了,直接写个博客介绍算了,并把代码放本博客里了。

安装方式

这里只有 windows 教程,linux 应该也是相似的。

需要至少两个 QQ 号,其中一个用作 bot,另一个用于控制 bot。用作 bot 的号是用来爬取的,故请保证 bot 号加了你要爬取的群聊。

下面的操作中,请保证电脑上没有预先登录用作 bot 的号,否则无法启动。用于控制 bot 的号可以登录在电脑上。

先按照 Ncatbot 官方文档 安装 Ncatbot 并试运行,完全按照官方文档里的指示走即可。

下面称 main.py 所在的文件夹(也就是 ncatbot 文件夹)为主文件夹。

然后在主文件夹下已有的 plugins 子文件夹里新建名为 message_fetcher 的子文件夹,在里面分别新建 __init__.py 和 message_fetcher.py,内容分别为:

__init__.py:

Python
from .message_fetcher import MessageFetcher

__all__ = ["MessageFetcher"]

message_fetcher.py:

Python
from ncatbot.plugin_system import NcatBotPlugin
from ncatbot.plugin_system import command_registry
from ncatbot.plugin_system import group_filter, admin_filter
from ncatbot.plugin_system import option, param
from ncatbot.core.event import BaseMessageEvent
from ncatbot.utils import get_log
from ncatbot.utils import ncatbot_config
import traceback, json, datetime
LOG = get_log(__name__)

def timestamp_to_readable_format(ti):
	return datetime.datetime.fromtimestamp(ti).strftime("%Y-%m-%d %H:%M:%S")

class MessageFetcher(NcatBotPlugin):
	name = "message_fetcher"
	version = "1.0.0"

	async def on_load(self):
		print(f"{self.name} 插件启动成功")

	@admin_filter
	@command_registry.command("fetch_count")
	@param(name="gid", help="要爬取的群号")
	@param(name="cnt", help="要爬取的消息数,默认为 20")
	@option(short_name="s", long_name="save", help="是否保存到本地,默认为真")
	@param(name="message_seq", help="开始爬取的消息id,不填即为最后一条消息开始爬取")
	async def fetch_count(self, event: BaseMessageEvent, gid: str, cnt: int = 20, save: bool = True, message_seq: str = 0):
		print(f"已收到爬取群聊 {gid} 的消息的请求,爬取消息数量为 {cnt},是否保存到本地为 {save},开始爬取的消息 id 为 {message_seq}。")
		try:
			if save:
				# 生成时间戳,避免覆盖文件
				now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
				txt_all_file = f"group_{gid}_msgs_{now}_all.txt"
				raw_msg_file = f"group_{gid}_msgs_{now}_raw.txt"
				await event.reply(f"消息将被保存到:\n文本文件:{txt_all_file}\n纯消息:{raw_msg_file}")

			msgs = await self.api.get_group_msg_history(group_id = gid, message_seq = int(message_seq), count = cnt, reverseOrder = True)
			# print(msgs)

			if save:
				# 保存为文本文件
				with open(txt_all_file, "w", encoding="utf-8") as f:
					f.write(f"爬取群聊 {gid} 的消息,爬取消息数量为 {cnt},是否保存到本地为 {save},开始爬取的消息 id 为 {message_seq}。\n\n")
					for msg in msgs:
						f.write(f"time={timestamp_to_readable_format(int(msg.time))}, timestamp={int(msg.time)}, " + str(msg) + "\n")  # 每条消息占一行
				with open(raw_msg_file, "w", encoding="utf-8") as f:
					f.write(f"爬取群聊 {gid} 的消息,爬取消息数量为 {cnt},是否保存到本地为 {save},开始爬取的消息 id 为 {message_seq}。\n\n")
					for msg in msgs:
						f.write(timestamp_to_readable_format(int(msg.time)) + " " + msg.raw_message + "\n")  # 每条消息占一行

			# print(int(msgs[0].message_id))

			await event.reply("已成功爬取消息")
		except Exception as e:
			tb_str = traceback.format_exc()
			error_msg = f"[warn] 无法爬取群 {gid} 的消息: \n{tb_str}"
			print(error_msg)
			await event.reply(error_msg)

	@admin_filter
	@command_registry.command("fetch_time")
	@param(name="gid", help="要爬取的群号")
	@param(name="start_ts", help="起始时间戳,秒级")
	@param(name="end_ts", help="结束时间戳,秒级")
	@option(short_name="s", long_name="save", help="是否保存到本地,默认为真")
	@param(name="message_seq", help="开始爬取的消息id,不填即为最后一条消息开始爬取")
	async def fetch_time(self, event: BaseMessageEvent, gid: str, start_ts: int, end_ts: int = 10000000000000000000, save: bool = True, message_seq: str = 0):
		print(f"收到爬取群聊 {gid} 从 {start_ts} 到 {end_ts} 的消息请求,是否保存到本地为 {save},开始爬取的消息 id 为 {message_seq}。")

		all_msgs_sz = 0
		last_seq = message_seq  # 从 0 开始抓取
		batch_size = 20  # 每次抓取条数,可调整
		next_time_batch_size = batch_size

		if save:
			# 生成时间戳,避免覆盖文件
			now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
			txt_all_file = f"group_{gid}_msgs_{now}_all.txt"
			raw_msg_file = f"group_{gid}_msgs_{now}_raw.txt"
			await event.reply(f"消息将被保存到:\n文本文件:{txt_all_file}\n纯消息:{raw_msg_file}")
			with open(txt_all_file, "a", encoding="utf-8") as f:
				f.write(f"爬取群聊 {gid} 从 {start_ts}({timestamp_to_readable_format(start_ts)}) 到 {"最后一条消息" if end_ts == 10000000000000000000 else f"{end_ts}({timestamp_to_readable_format(end_ts)})"} 的消息,是否保存到本地为 {save},开始爬取的消息 id 为 {message_seq}。\n\n")
			with open(raw_msg_file, "a", encoding="utf-8") as f:
				f.write(f"爬取群聊 {gid} 从 {start_ts}({timestamp_to_readable_format(start_ts)}) 到 {"最后一条消息" if end_ts == 10000000000000000000 else f"{end_ts}({timestamp_to_readable_format(end_ts)})"} 的消息,是否保存到本地为 {save},开始爬取的消息 id 为 {message_seq}。\n\n")

		try:
			while True:
				msgs = await self.api.get_group_msg_history(
					group_id=gid,
					message_seq=last_seq,
					count=next_time_batch_size,
					reverseOrder=True
				)

				if not msgs:
					break  # 没有更多消息

				# 更新 last_seq,防止重复抓取
				if int(msgs[0].message_id) == last_seq:
					await event.reply(f"爬取时出现 bug,尝试爬取连续的 {next_time_batch_size} 条消息时,前后两次爬取都卡在同一条消息了。这可能是由于有较多条连续的戳一戳导致的,现在将尝试增大一次爬取的连续消息数量以趟过这些消息。如果您多次看到这条消息,请终止程序(直接退出终端即可)。")
					next_time_batch_size += 5
					continue
				next_time_batch_size = batch_size
				last_seq = int(msgs[0].message_id)

				# 根据时间戳筛选
				filtered = [m for m in msgs if start_ts <= m.time <= end_ts and m.message_id != last_seq]
				filtered.reverse()
				lst_all_msgs_sz = all_msgs_sz
				all_msgs_sz += len(filtered)

				# print(f"已爬取 {all_msgs_sz} 条消息")
				if all_msgs_sz // 1000 > lst_all_msgs_sz // 1000:
					print(f"已爬取 {all_msgs_sz} 条消息,目前爬取到的最后一条消息的时间为 {timestamp_to_readable_format(int(msgs[0].time))} ")
					# await event.reply(f"已爬取 {all_msgs_sz} 条消息,目前爬取到的最后一条消息的时间为 {timestamp_to_readable_format(int(msgs[0].time))}")

				if save:
					# 追加写入文本文件
					with open(txt_all_file, "a", encoding="utf-8") as f:
						for msg in filtered:
							f.write(f"time={timestamp_to_readable_format(int(msg.time))}, timestamp={int(msg.time)}, " + str(msg) + "\n")  # 每条消息占一行
					with open(raw_msg_file, "a", encoding="utf-8") as f:
						for msg in filtered:
							f.write(timestamp_to_readable_format(int(msg.time)) + " " + msg.raw_message + "\n")  # 每条消息占一行

				# print(msgs[0].time)
				# 如果倒序,且最后一条消息小于 start_ts,停止
				if int(msgs[0].time) < start_ts:
					break

			print(f"共抓取到 {all_msgs_sz} 条符合条件的消息")
			await event.reply(f"已成功爬取 {all_msgs_sz} 条消息")

			if save:
				# await event.reply(f"消息已保存:\n文本文件:{txt_file}")
				await event.reply(f"消息已保存到:\n文本文件:{txt_all_file}\n纯消息:{raw_msg_file}")

		except Exception as e:
			import traceback
			tb_str = traceback.format_exc()
			error_msg = f"[warn] 无法爬取群 {gid} 的消息: \n{tb_str}"
			print(error_msg)
			await event.reply(error_msg)

并将主文件夹下的 main.py 最后一句 bot.run() 改为 bot.run_frontend()。

打开主文件夹下的 config.yaml,将第一句 root:'123456' 里的 123456 改为用来控制 bot 的 QQ 号。

此时的文件夹结构应如下所示:

代码
ncatbot
├───data
│   ├───此处省略
├───logs
├───napcat
│   ├───此处省略
├───plugins
│   └───message_fetcher
│       ├───__init__.py
│       └───message_fetcher.py
├───config.yaml
└───main.py

然后在主文件夹下启动 cmd,输入 python main.py 即可启动。

这会额外打开一个终端,并可能会请求管理员权限。运行时同时需要这两个终端,不能只保留一个。要想结束程序,将两个终端都关掉即可。

启动大约需要半分钟,当看到形如以下输出后,波特才会生效,在此之前向波特发送命令都不会有反应。

代码
[18:42:12.714] INFO     [MainThread|MainProcess] Adapter logger.py:info:129 | NapCat WebSocket 连接成功
[18:42:12.715] INFO     [Thread-2 (_worker_loop)|MainProcess] Client logger.py:info:129 | Bot "用作 bot 的QQ号" 启动成功

使用方法

用控制 bot 的号向 bot 号发送指令。指令有以下两种,不带“默认”的是必填参数:

  • /fetch_count 要爬取的群号 要爬取的消息数(默认为 20) 是否保存到本地(默认为真) 开始爬取的消息id(不填即为最后一条消息开始爬取):爬取指定数量的消息

  • /fetch_time 要爬取的群号 起始时间戳(秒级) 结束时间戳(秒级)(如未指定,默认爬取到最后一条消息) 是否保存到本地(默认为真) 开始爬取的消息id(不填即为最后一条消息开始爬取):爬取指定时间区间里的消息

注意,这两条爬取都是从后往前爬的,目前还不支持从前往后爬。并且这两条指令默认都会从群聊中的最后一条消息开始往前爬取,即使 fetch_time 指定了结束时间戳,它也会从最后一条消息(而非结束时间戳之前的最后一条)往前跳链表。 要想继续着上次的爬取继续爬,可以从上次爬取的导出文件里获得最后一条消息的 message_id,填入最后一个参数(开始爬取的消息id)。 疑似 api 有个 bug,开始爬的消息必须在当前 bot 运行的生命周期里曾经被爬取到才行。受限于 api 限制,本人目前还不知道怎么二分消息,只能烦请群友加以改进了。

目前还不支持参数输入格式化的时间,python 大手子可以自行改编。

是否保存到本地(默认为真) 这项参数为 True 和 False 其中之一,因为是用 python 写的。

导出文件位于主文件夹下的根目录。由于我是把 python 里消息的结构体直接输出了,故而观感十分甚至九分的不好,体积也比较庞大,还请谅解,但是毕竟只是用作爬取用,并且已经足够喂给 AI 吃了,就没再管。群友可以自行更改代码以适应导出需求。

每爬取 1000 条消息会在 QQ 里向控制 bot 的号发送一条消息,指示当前爬的最后一条消息的时间,方便获知爬取进度。觉得烦的群友,将 message_fetcher.py 里这两行注释掉即可:

Python
if len(all_msgs) // 1000 > lst_all_msgs_sz // 1000:
	await event.reply(f"已爬取 {len(all_msgs)} 条消息,目前爬取到的最后一条消息的时间为 {datetime.datetime.fromtimestamp(int(msgs[0].time)).strftime("%Y-%m-%d %H:%M:%S")}")

不保证不会出现漏消息的情况,还请谅解。(有次测试,两次爬 U 群 2025.10.10 0:00:00 到 2025.10.27 晚上的消息,第一次 batch_size 为 10,爬到了 26671 条消息,第二次 batch_size 为 5,爬到了 30929 条消息 /jk)

要加快爬取速度,可以增大 message_fetcher.py 里 batch_size 变量的值。但是注意,如果 batch_size 过大,爬取的消息数量太大(例如爬到了几十条包含 100 条消息的转发消息),可能会导致单次爬取失败。

由于 QQ api 不是很稳定,爬取有时会报错(并且报错不一定会在 QQ 里向控制 bot 的号发送消息,可能是在终端里报错),建议重启 ncatbot 多尝试几次,说不定就好了。

已知 bug

遇到连续的多个戳一戳时会卡在这条消息处不停爬取。如果您在 bot 发送的指示进度的消息里,看到连续两次爬取 1000 条消息时,最后一条消息的时间相同,就很可能是出了这个 bug 了。

解决办法有:

  • 从导出文件里获得最后一条消息的 message_id,从这条消息开始爬。
  • 程序会向控制 bot 的号发送报告,并自己尝试增大单次爬取的消息数量以趟过去。如果您连续很多次看见「前后两次爬取都卡在同一条消息了」的报告,可能是趟不过去了 /ll
原文