File size: 2,397 Bytes
720aed0 6e04ee1 1f6f712 38e2b20 6e04ee1 d69caf7 6e04ee1 720aed0 ed4ae38 720aed0 24797b4 720aed0 24797b4 720aed0 24797b4 720aed0 24797b4 ed4ae38 38e2b20 1f6f712 38e2b20 8ebe831 b8986b1 8ebe831 38e2b20 1f6f712 38e2b20 6fa4701 | 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 | import os
import re
from dotenv import load_dotenv
# 加载 .env 环境变量(针对本地运行)
load_dotenv()
import nonebot
from nonebot.adapters.qq import Adapter as QQAdapter
from nonebot.adapters.qq.message import Message, MessageSegment
# 预编译匹配 URL 的正则,用来删除URL
URL_REGEX = re.compile(
r"(http|https)://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(/[a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~]*)?"
)
# 初始化 NoneBot
# 显式配置驱动器并开启沙盒模式
# 同时在这里直接通过代码填入 Intent,防止环境变量解析出问题
nonebot.init(
driver="~fastapi+~httpx+~websockets",
qq_is_sandbox=True,
orm_upgrade_on_start=True, # 开启启动时自动升级数据库迁移
qq_bots=[
{
"id": os.getenv("QQ_APP_ID"),
"token": os.getenv("QQ_TOKEN"),
"secret": os.getenv("QQ_SECRET"),
# 开启所有核心消息意图
"intent": {
"c2c_group_at_messages": True, # 群聊@机器人消息
"direct_message": True, # 私聊消息
"at_messages": True, # 频道@机器人消息
"guild_messages": True, # 频道消息
},
}
],
)
# 注册适配器
driver = nonebot.get_driver()
driver.register_adapter(QQAdapter)
from nonebot.adapters import Bot
# 注册全局 API 调用钩子,拦截并清理消息中的 URL
@Bot.on_calling_api
async def handle_api_call(bot, api, data):
# 针对发送消息的接口进行处理
if api in ["post_group_messages", "post_c2c_messages", "post_messages"]:
if "content" in data and isinstance(data["content"], str):
# 直接删除所有 URL
data["content"] = URL_REGEX.sub("", data["content"])
# 如果消息是 Message 对象,也需要处理其中的文本段
if "message" in data:
msg = data["message"]
if isinstance(msg, str):
data["message"] = URL_REGEX.sub("", msg)
# 加载内置插件
nonebot.load_builtin_plugins("echo")
# 加载第三方插件
nonebot.load_plugin("nonebot_plugin_skland")
nonebot.load_plugin("haruka_bot")
# 如果你有自定义插件目录,可以这样加载
nonebot.load_plugin("src.plugins.order_notifier")
if __name__ == "__main__":
# Hugging Face 必须监听 7860 端口
nonebot.run(host="0.0.0.0", port=7860)
|