-
Notifications
You must be signed in to change notification settings - Fork 0
Add /warn command #135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Add /warn command #135
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,32 @@ | ||||||||||||||||||||||||||||||||||||||
| version: '3.8' | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| services: | ||||||||||||||||||||||||||||||||||||||
| redis: | ||||||||||||||||||||||||||||||||||||||
| image: redis:7-alpine | ||||||||||||||||||||||||||||||||||||||
| container_name: redis_db | ||||||||||||||||||||||||||||||||||||||
| restart: always | ||||||||||||||||||||||||||||||||||||||
| command: redis-server --requirepass "Radmin" | ||||||||||||||||||||||||||||||||||||||
| ports: | ||||||||||||||||||||||||||||||||||||||
| - "6379:6379" | ||||||||||||||||||||||||||||||||||||||
| volumes: | ||||||||||||||||||||||||||||||||||||||
| - redis_data:/data | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| influxdb: | ||||||||||||||||||||||||||||||||||||||
| image: influxdb:2.7-alpine | ||||||||||||||||||||||||||||||||||||||
| container_name: influx_db | ||||||||||||||||||||||||||||||||||||||
| restart: always | ||||||||||||||||||||||||||||||||||||||
| ports: | ||||||||||||||||||||||||||||||||||||||
| - "8086:8086" | ||||||||||||||||||||||||||||||||||||||
| environment: | ||||||||||||||||||||||||||||||||||||||
| - DOCKER_INFLUXDB_INIT_MODE=setup | ||||||||||||||||||||||||||||||||||||||
| - DOCKER_INFLUXDB_INIT_USERNAME=Iadmin | ||||||||||||||||||||||||||||||||||||||
| - DOCKER_INFLUXDB_INIT_PASSWORD=Iadmin1234567 | ||||||||||||||||||||||||||||||||||||||
| - DOCKER_INFLUXDB_INIT_ORG=polinetwork | ||||||||||||||||||||||||||||||||||||||
| - DOCKER_INFLUXDB_INIT_BUCKET=telegram_bot | ||||||||||||||||||||||||||||||||||||||
| - DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=tu_token_secreto_de_32_caracteres_o_mas | ||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+18
to
+26
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win Move InfluxDB admin credentials out of the compose file. The admin password/token are committed and the service is exposed on all interfaces. Since telemetry depends on Suggested change ports:
- - "8086:8086"
+ - "127.0.0.1:8086:8086"
environment:
- DOCKER_INFLUXDB_INIT_MODE=setup
- - DOCKER_INFLUXDB_INIT_USERNAME=Iadmin
- - DOCKER_INFLUXDB_INIT_PASSWORD=Iadmin1234567
+ - DOCKER_INFLUXDB_INIT_USERNAME=${INFLUXDB_INIT_USERNAME:?INFLUXDB_INIT_USERNAME must be set}
+ - DOCKER_INFLUXDB_INIT_PASSWORD=${INFLUXDB_INIT_PASSWORD:?INFLUXDB_INIT_PASSWORD must be set}
- DOCKER_INFLUXDB_INIT_ORG=polinetwork
- DOCKER_INFLUXDB_INIT_BUCKET=telegram_bot
- - DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=tu_token_secreto_de_32_caracteres_o_mas
+ - DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=${INFLUXDB_TOKEN:?INFLUXDB_TOKEN must be set}📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||
| volumes: | ||||||||||||||||||||||||||||||||||||||
| - influxdb_data:/var/lib/influxdb2 | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| volumes: | ||||||||||||||||||||||||||||||||||||||
| redis_data: | ||||||||||||||||||||||||||||||||||||||
| influxdb_data: | ||||||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,9 +6,9 @@ | |
| "main": "./dist/bot.js", | ||
| "type": "module", | ||
| "scripts": { | ||
| "start": "NODE_ENV=production node dist/bot.js", | ||
| "start": "cross-env NODE_ENV=production node dist/bot.js", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Verify whether runtime scripts depend on dev-only binaries.
node - <<'NODE'
const pkg = require('./package.json')
const startUsesCrossEnv = /\bcross-env\b/.test(pkg.scripts?.start || '')
const inDeps = Boolean(pkg.dependencies?.['cross-env'])
const inDevDeps = Boolean(pkg.devDependencies?.['cross-env'])
console.log({ startUsesCrossEnv, inDeps, inDevDeps })
if (startUsesCrossEnv && !inDeps) {
process.exitCode = 1
}
NODERepository: PoliNetworkOrg/telegram Length of output: 221 Move 🤖 Prompt for AI Agents |
||
| "build": "tsup", | ||
| "dev:raw": "NODE_ENV=development tsx watch --clear-screen=false --env-file=.env src/bot.ts", | ||
| "dev:raw": "cross-env NODE_ENV=development tsx watch --clear-screen=false --env-file=.env src/bot.ts", | ||
| "dev": "pnpm run dev:raw | pino-pretty", | ||
| "test": "vitest run", | ||
| "typecheck": "tsgo --noEmit", | ||
|
|
@@ -23,6 +23,7 @@ | |
| "@trpc/server": "11.5.1", | ||
| "@types/node": "^24.12.2", | ||
| "@typescript/native-preview": "7.0.0-dev.20260421.2", | ||
| "cross-env": "^7.0.3", | ||
| "pino-pretty": "^13.0.0", | ||
| "ts-node": "^10.9.2", | ||
| "tsup": "^8.4.0", | ||
|
|
@@ -38,7 +39,7 @@ | |
| "@grammyjs/parse-mode": "^1.11.1", | ||
| "@grammyjs/runner": "^2.0.3", | ||
| "@influxdata/influxdb-client": "^1.35.0", | ||
| "@polinetwork/backend": "^0.15.18", | ||
| "@polinetwork/backend": "file:../backend/package", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Verify whether the local file dependency is resolvable in this checkout.
node - <<'NODE'
const fs = require('fs')
const path = require('path')
const pkg = require('./package.json')
const spec = pkg.dependencies?.['`@polinetwork/backend`']
console.log({ spec })
if (spec?.startsWith('file:')) {
const target = path.resolve(process.cwd(), spec.slice('file:'.length))
console.log({ target, exists: fs.existsSync(target) })
if (!fs.existsSync(target)) process.exitCode = 1
}
NODERepository: PoliNetworkOrg/telegram Length of output: 257 Avoid the sibling-local backend dependency. 🤖 Prompt for AI Agents |
||
| "@socket.io/devalue-parser": "^0.1.0", | ||
| "@t3-oss/env-core": "^0.13.4", | ||
| "@trpc/client": "^11.5.1", | ||
|
|
||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,261 @@ | ||
| import { CommandsCollection } from "@/lib/managed-commands" | ||
| import { logger } from "@/logger" | ||
| import { modules } from "@/modules" | ||
| import { Moderation } from "@/modules/moderation" | ||
| import { fmt } from "@/utils/format" | ||
| import { ephemeral } from "@/utils/messages" | ||
| import { numberOrString, tgnumber, type MaybePromise, type PartialMessage, type Role } from "@/utils/types" | ||
| import { getOverloadUser, resolveUser } from "@/utils/users" | ||
| import { api } from "@/backend" | ||
|
|
||
|
|
||
| export type Warning = { | ||
| id: number; | ||
| targetId: number; | ||
| adminId: number; | ||
| groupId: number; | ||
| reason: string | null; | ||
| isExpired: boolean; | ||
| deletedAt: Date | null; | ||
| createdAt: Date; | ||
| group: { | ||
| title: string; | ||
| inviteLink: string | null; | ||
| } | null; | ||
| admin: { | ||
| id: number; | ||
| firstName: string; | ||
| lastName?: string; | ||
| username?: string; | ||
| isBot: boolean; | ||
| langCode?: string; | ||
| } | null; | ||
| target: { | ||
| id: number; | ||
| firstName: string; | ||
| lastName?: string; | ||
| username?: string; | ||
| isBot: boolean; | ||
| langCode?: string; | ||
| } | null; | ||
| }; | ||
|
|
||
| async function ephemeralInGroup(ctx: { chat: { type: string } }, message: MaybePromise<PartialMessage>) { | ||
| if (ctx.chat.type === "private") { | ||
| await message | ||
| } else { | ||
| void ephemeral(message) | ||
| } | ||
| } | ||
|
|
||
| export const warn = new CommandsCollection<Role>("Warning") | ||
| .createCommand({ | ||
| trigger: "warn", | ||
| args: [ | ||
| { | ||
| key: "reasonOrUser", | ||
| optional: true, | ||
| description: | ||
| "If the message is a reply, this argument is the reason. Otherwise, it's the username or user id of the user to warn", | ||
| type: numberOrString, | ||
| }, | ||
| { | ||
| key: "reason", | ||
| optional: true, | ||
| description: "Optional reason to warn the user", | ||
| }, | ||
| ], | ||
| description: "Warn a user from a group", | ||
| scope: "both", | ||
| permissions: { | ||
| allowedRoles: ["owner", "direttivo"], | ||
| excludedRoles: ["creator"], | ||
| allowGroupAdmins: true, | ||
| }, | ||
| handler: async ({ args, context, repliedTo }) => { | ||
|
Comment on lines
+68
to
+75
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win Restrict With Also applies to: 90-95 🤖 Prompt for AI Agents |
||
| const userOverload = await getOverloadUser(context, repliedTo ?? null, args.reasonOrUser, args.reason) | ||
| if (userOverload.isErr()) { | ||
| await ephemeralInGroup(context, context.reply( | ||
| repliedTo | ||
| ? fmt(({ n }) => n`There was an error`) | ||
| : fmt(({ n }) => n`Target user not found, please try replying to their message`) | ||
| )) | ||
| logger.error({ args, repliedTo }, `WARN: ${userOverload.error}`) | ||
| return | ||
| } | ||
|
|
||
| const { user, reason } = userOverload.value | ||
|
|
||
| try { | ||
| const { error } = await api.tg.warnings.create.mutate({ | ||
| targetId: user.id, | ||
| adminId: context.from.id, | ||
| groupId: context.chat.id, | ||
| reason | ||
| }) | ||
|
|
||
| if (error) { | ||
| await ephemeralInGroup(context, context.reply(fmt(({ n }) => n`There was an error: ${error}`))) | ||
| return | ||
| } | ||
| } catch (error) { | ||
| logger.error({ error }, "Failed to warn user") | ||
| await ephemeralInGroup(context, context.reply(fmt(({ n }) => n`There was an error: ${String(error)}`))) | ||
| return | ||
| } | ||
|
|
||
| const extraLines: string[] = [] | ||
|
|
||
| if (context.chat.type === "group" || context.chat.type === "supergroup") { | ||
| try { | ||
| const [groupCount] = await api.tg.warnings.getActiveCountInGroup.query({ | ||
| targetId: user.id, | ||
| groupId: context.chat.id, | ||
| }) | ||
| if (groupCount.count >= 3) { | ||
| const kickRes = await Moderation.kick(user, context.chat, context.from, [], "Auto-kick: 3 warnings in this group") | ||
| if (kickRes.isOk()) { | ||
| extraLines.push("👢 Auto-kicked (3 warnings in this group)") | ||
| } | ||
| } | ||
| } catch (error) { | ||
| logger.error({ error, targetId: user.id, groupId: context.chat.id }, "Auto-kick check failed after warning") | ||
| } | ||
| } | ||
|
|
||
| try { | ||
| const [totalCount] = await api.tg.warnings.getTotalActiveCount.query({ | ||
| targetId: user.id, | ||
| }) | ||
| if (totalCount.count >= 4) { | ||
| await modules.get("tgLogger").banAll(user, context.from, "BAN", "Auto-ban all: 4 total warnings") | ||
| extraLines.push("🚫 Auto-ban all initiated (4 total warnings)") | ||
|
itasimo marked this conversation as resolved.
itasimo marked this conversation as resolved.
|
||
| } | ||
| } catch (error) { | ||
| logger.error({ error, targetId: user.id }, "Auto-ban all check failed after warning") | ||
| } | ||
|
|
||
| await ephemeralInGroup(context, context.reply( | ||
| fmt(({ b, n, i }) => [ | ||
| b`⚠️ User has been warned!`, | ||
| n`${b`Target:`} ${user.username ? `@${user.username}` : user.first_name}`, | ||
| ...(reason ? [n`${b`Reason:`} ${i`${reason}`}`] : []), | ||
| ...(extraLines.length > 0 ? ["", ...extraLines.map(l => n`${l}`)] : []), | ||
| ], { | ||
| sep: "\n", | ||
| }) | ||
| )) | ||
| } | ||
| }) | ||
| .createCommand({ | ||
| trigger: "unwarn", | ||
| args: [{ key: "warnId", type: tgnumber, description: "Warning ID to remove (use /warns to get the ID)" }], | ||
| description: "Remove a warning by its ID", | ||
| scope: "both", | ||
| permissions: { | ||
| allowedRoles: ["owner", "direttivo"], | ||
| excludedRoles: ["creator"], | ||
| allowGroupAdmins: true, | ||
| }, | ||
| handler: async ({ args, context }) => { | ||
| const warnId = Number(args.warnId) | ||
|
|
||
| if (Number.isNaN(warnId)) { | ||
| await ephemeralInGroup(context, context.reply(fmt(({ n }) => n`Invalid Warning ID. Use /warns to get the correct numeric ID.`))) | ||
| return | ||
| } | ||
|
|
||
| try { | ||
| const res = await api.tg.warnings.deleteById.mutate({ | ||
| id: warnId | ||
| }) | ||
|
Comment on lines
+168
to
+171
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift
This mutation only sends 🤖 Prompt for AI Agents |
||
|
|
||
| if (res?.deleted === false) { | ||
| await ephemeralInGroup(context, context.reply( | ||
| fmt(({ n }) => n`That warning was already removed, expired or doesn't exist.`) | ||
| )) | ||
| return | ||
| } | ||
|
|
||
| await ephemeralInGroup(context, context.reply( | ||
| fmt(({ b, n }) => [ | ||
| b`✅ Warning removed!`, | ||
| n`Warning with ID ${b`#${warnId}`} has been lifted.` | ||
| ], { | ||
| sep: "\n", | ||
| }) | ||
| )) | ||
| } catch (error) { | ||
| logger.error({ warnId, error }, "Failed to delete warning") | ||
| await ephemeralInGroup(context, context.reply(fmt(({ n }) => n`There was an error: ${String(error)}`))) | ||
| } | ||
| }, | ||
| }) | ||
| .createCommand({ | ||
| trigger: "warns", | ||
| description: "Get the warnings of a user", | ||
| scope: "private", | ||
| args: [{ key: "username", type: numberOrString, description: "Username (or user id) to get the warnings of" }], | ||
| permissions: { | ||
| allowedRoles: ["owner", "direttivo"], | ||
| excludedRoles: ["creator"], | ||
| }, | ||
| handler: async ({ args, context }) => { | ||
|
|
||
| const user = await resolveUser(args.username, context) | ||
| if (!user) return | ||
|
|
||
| try { | ||
| const warns: Warning[] = await api.tg.warnings.getByTarget.query({ | ||
| targetId: user.id, | ||
| }) | ||
|
|
||
| if (warns.length === 0) { | ||
| return void await context.reply( | ||
| fmt(({ n }) => n`${user.username || user.first_name} has clean records (0 warnings).`) | ||
| ) | ||
| } | ||
|
|
||
| await context.reply( | ||
| fmt(({ b, n, i, code }) => { | ||
| const elements = [ | ||
| b`⚠️ Warning history for @${user.username || user.first_name}:`, | ||
| `Total Warnings: ${warns.length}`, | ||
| "", | ||
| ]; | ||
|
|
||
| warns.forEach((warn, index) => { | ||
| const date = new Date(warn.createdAt).toLocaleDateString(); | ||
| const status = warn.isExpired ? "🟢 [Expired]" : warn.deletedAt ? "🗑️ [Removed]" : "🔴 [Active]"; | ||
|
|
||
| const warningId = warn.id | ||
| const groupName = warn.group?.title || `Group ID: ${warn.groupId}`; | ||
| const adminName = warn.admin?.firstName | ||
| ? `@${warn.admin.username || warn.admin.firstName}` | ||
| : `ID: ${warn.adminId}`; | ||
|
|
||
| elements.push( | ||
| `${index + 1}. ${status} - ${date}`, | ||
| n` 🆔 ${b`Warning ID:`} ${code`${warningId}`}`, | ||
| n` 👥 ${b`Group:`} ${groupName}`, | ||
| n` 👮♂️ ${b`Admin:`} ${adminName}`, | ||
| n` 📝 ${b`Reason:`} ${warn.reason ? i`${warn.reason}` : "No reason provided"}` | ||
| ) | ||
|
|
||
| if (index < warns.length - 1) { | ||
| elements.push(""); | ||
| } | ||
| }); | ||
|
|
||
| return elements; | ||
| }, { | ||
| sep: "\n", | ||
| }) | ||
| ) | ||
| } catch (error) { | ||
| logger.error({ error }, "Failed to fetch warnings") | ||
| await context.reply(fmt(({ n }) => n`There was an error: ${String(error)}`)) | ||
| } | ||
| }, | ||
| }) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Avoid hardcoded Redis credentials on a host-exposed port.
Radminis committed and Redis is published on all interfaces; it also has to matchREDIS_PASSWORDfromsrc/redis/index.ts, or the app cannot authenticate. Use an env-substituted secret and bind locally for dev.Suggested change
📝 Committable suggestion
🤖 Prompt for AI Agents