Skip to content

Commit

Permalink
Merge pull request #43 from kabo2468/develop
Browse files Browse the repository at this point in the history
  • Loading branch information
kabo2468 authored Jan 28, 2025
2 parents de5bc3a + b1e7b09 commit ad71ef2
Show file tree
Hide file tree
Showing 13 changed files with 274 additions and 21 deletions.
17 changes: 17 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.idea
**/.vscode
**/.cache
**/docker-compose*
**/compose.y*ml
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/secrets.dev.yaml
**/values.dev.yaml
**/built
LICENSE
README.md
95 changes: 95 additions & 0 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
name: Docker

# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

on:
push:
# Publish semver tags as releases.
tags: [ 'v*.*.*' ]

env:
# Use docker.io for Docker Hub if empty
REGISTRY: ghcr.io
# github.repository as <account>/<repo>
IMAGE_NAME: ${{ github.repository }}


jobs:
build:

runs-on: ubuntu-latest
permissions:
contents: read
packages: write
# This is used to complete the identity challenge
# with sigstore/fulcio when running outside of PRs.
id-token: write

steps:
- name: Checkout repository
uses: actions/checkout@v4

# Install the cosign tool except on PR
# https://github.com/sigstore/cosign-installer
- name: Install cosign
if: github.event_name != 'pull_request'
uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 #v3.5.0
with:
cosign-release: 'v2.2.4'

# Set up BuildKit Docker container builder to be able to build
# multi-platform images and export cache
# https://github.com/docker/setup-buildx-action
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0

# Login against a Docker registry except on PR
# https://github.com/docker/login-action
- name: Log into registry ${{ env.REGISTRY }}
if: github.event_name != 'pull_request'
uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

# Extract metadata (tags, labels) for Docker
# https://github.com/docker/metadata-action
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

# Build and push Docker image with Buildx (don't push on PR)
# https://github.com/docker/build-push-action
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
GIT_SHA=${{ github.sha }}
# Sign the resulting Docker image digest except on PRs.
# This will only write to the public Rekor transparency log when the Docker
# repository is public to avoid leaking data. If you would like to publish
# transparency data even for private images, pass --force to cosign below.
# https://github.com/sigstore/cosign
- name: Sign the published Docker image
if: ${{ github.event_name != 'pull_request' }}
env:
# https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable
TAGS: ${{ steps.meta.outputs.tags }}
DIGEST: ${{ steps.build-and-push.outputs.digest }}
# This step uses the identity token to provision an ephemeral certificate
# against the sigstore community Fulcio instance.
run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ node_modules
.vscode
test
built
config.json5
config.*
mecab
valentine.json

.idea/*
*.secret
53 changes: 53 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
FROM node:22-slim AS base

ARG GIT_SHA="unknown"
ENV GIT_SHA=$GIT_SHA

ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"

RUN corepack enable

FROM base AS init
COPY . /app
WORKDIR /app

# hadolint ignore=DL3008
RUN apt-get update \
&& apt-get install -y --no-install-recommends g++ gcc make python3 \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*

FROM init AS prod-deps
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --prod --frozen-lockfile

FROM init AS build
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile \
&& pnpm run build

FROM base
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
# hadolint ignore=DL3008
RUN apt-get update \
&& apt-get install -y --no-install-recommends mecab libmecab-dev mecab-ipadic-utf8 \
git make curl ca-certificates xz-utils file patch sudo openssl \
&& git clone --depth 1 https://github.com/neologd/mecab-ipadic-neologd.git \
&& cd mecab-ipadic-neologd \
&& curl https://patch-diff.githubusercontent.com/raw/neologd/mecab-ipadic-neologd/pull/91.patch | git apply -v \
&& ./bin/install-mecab-ipadic-neologd -n -y -a \
&& cd .. \
&& rm -rf mecab-ipadic-neologd \
&& apt-get purge -y --auto-remove git make curl ca-certificates xz-utils file patch openssl \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*

ENV NODE_ENV=production
WORKDIR /app

COPY --from=prod-deps /app/node_modules /app/node_modules
COPY --from=build /app/built /app/built
COPY config.json5 ngwords.txt package.json /app/

RUN chown -R node:node /app
USER node
CMD ["pnpm", "migrateandstart"]
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ TLから言葉を学び、それをおいしいかまずいか決めて、投稿

## 使い方

Docker を使う場合は、[Docker](#docker) を参照してください。

### Misskey で @oishiibot を作る

この ID じゃないと動きません
Expand Down Expand Up @@ -97,3 +99,17 @@ npm start
Xeltica さんの Citrine から参考にさせていただきました。

<https://github.com/Xeltica/Citrine/blob/master/Resources/ngwords.txt>

## Docker

Dockerを使う場合は、以下の手順で起動できます。

1. `example.docker.json5``config.json5` にコピーして編集する (上記の [config.json5](#config.json) を参照)
2. `db_password.secret.example` のように `db_password.secret` にDBのパスワードを書く
3. `docker compose up -d` で起動する

デフォルトでは、既にビルドされたイメージを使うようになっています。

ローカルのソースコードを使いたい場合は、`compose.yaml`内の`services.bot.image`をコメントアウトしてください。

ビルドするときは、`docker compose build --build-arg GIT_SHA=$(git rev-parse HEAD)` を実行してください。
40 changes: 40 additions & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
services:
bot:
image: ghcr.io/kabo2468/oishii-bot
build:
context: .
args:
- GIT_SHA=unknown
volumes:
- ./config.json5:/app/config.json5:ro
- ./valentine.json:/app/valentine.json:rw
depends_on:
db:
condition: service_healthy
restart: always

db:
image: postgres:alpine
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
environment:
- POSTGRES_DB=postgres
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
expose:
- 5432
healthcheck:
test: ["CMD", "pg_isready"]
interval: 10s
timeout: 5s
retries: 5

volumes:
db-data:

secrets:
db-password:
file: db_password.secret
1 change: 1 addition & 0 deletions db_password.secret.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PASSWORD
17 changes: 17 additions & 0 deletions example.docker.json5
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
url: 'https://misskey.io',
apiKey: '',
databaseUrl: 'postgresql://postgres:PASSWORD@db:5432/postgres',
dbSSL: false,
ownerUsernames: ['kabo'],
post: {
autoPostInterval: 60,
tlPostProbability: 0.4,
rateLimitSec: 60,
rateLimitPost: 5,
},
mecab: {
binPath: '/usr/bin/mecab',
dicPath: '/usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipadic-neologd',
},
}
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
"build": "npm run clean && npm run tsc",
"lint": "biome lint src --write",
"format": "biome format src --write",
"migration": "node built/migration.js"
"migration": "node built/migration.js",
"migrateandstart": "pnpm run migration && pnpm start"
},
"dependencies": {
"got": "^14.4.4",
"iconv-lite": "^0.6.3",
"json5": "^2.2.3",
"memory-streams": "^0.1.3",
"mfm-js": "^0.24.0",
Expand All @@ -48,5 +50,5 @@
"bufferutil": "^4.0.8",
"utf-8-validate": "^6.0.5"
},
"packageManager": "pnpm@9.13.2+sha512.88c9c3864450350e65a33587ab801acf946d7c814ed1134da4a924f6df5a2120fd36b46aab68f7cd1d413149112d53c7db3a4136624cfd00ff1846a0c6cef48a"
"packageManager": "pnpm@9.15.4+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0"
}
6 changes: 3 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,12 @@ export class Bot {
const learned = Math.random() < 0.2;
const res = await this.getRandomFood({ learned });

const food = res.rows[0].name;
const good = res.rows[0].good;
const food = res.rows[0]?.name;
const good = res.rows[0]?.good;
if (!food || good === undefined) {
this.log('sayFood: not found');
return;
}
this.log(`sayFood: ${food} (${good})`);

const text = messages.food.say(food, good);
Expand Down
28 changes: 18 additions & 10 deletions src/modules/commands/info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,30 @@ export default class extends Module {
text.push(`Node.js: ${process.version}`);

// Records
const fl = Number(res.rows[0].count);
const tl = Number(res.rows[1].count);
const fl = Number(res.rows[0]?.count) || 0;
const tl = Number(res.rows[1]?.count) || 0;
const all = fl + tl;
const recordText = `Records: ${all} (Learned: ${tl})`;
this.log(recordText);
text.push(recordText);

// Commit Hash
const rev = readFileSync('.git/HEAD').toString();
const branchHash = readFileSync('.git/' + rev.substring(5).trim())
.toString()
.trim();
const hash = rev.indexOf(':') === -1 ? rev : branchHash;
const hashText = `Commit hash: ${hash.substring(0, 7)}`;
this.log(hashText);
text.push(hashText);
if (process.env.GIT_SHA) {
this.log('from process.env.GIT_SHA');
const hashText = `Commit hash: ${process.env.GIT_SHA.substring(0, 7)}`;
this.log(hashText);
text.push(hashText);
} else {
this.log('from .git');
const rev = readFileSync('.git/HEAD').toString();
const branchHash = readFileSync('.git/' + rev.substring(5).trim())
.toString()
.trim();
const hash = rev.indexOf(':') === -1 ? rev : branchHash;
const hashText = `Commit hash: ${hash.substring(0, 7)}`;
this.log(hashText);
text.push(hashText);
}

// uptime
const uptime = process.uptime();
Expand Down
4 changes: 2 additions & 2 deletions src/modules/hungry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export default class extends Module {

const res = await bot.getRandomFood({ good: _g });

const food = res.rows[0].name;
const good = res.rows[0].good;
const food = res.rows[0]?.name;
const good = res.rows[0]?.good;
if (!food || good === undefined) {
note.reply({ text: messages.food.idk });
return;
Expand Down

0 comments on commit ad71ef2

Please sign in to comment.