Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea875e392f | ||
|
|
b89d98e42b |
@@ -13,7 +13,7 @@ coverage
|
||||
*.json5
|
||||
*.yaml
|
||||
*.yml
|
||||
*.env
|
||||
|
||||
|
||||
# exceptions
|
||||
!heroku.yml
|
||||
|
||||
1
.github/FUNDING.yml
vendored
@@ -1,3 +1,2 @@
|
||||
github: [FoxxMD]
|
||||
patreon: FoxxMD
|
||||
custom: ["bitcoincash:qqmpsh365r8n9jhp4p8ks7f7qdr7203cws4kmkmr8q"]
|
||||
|
||||
3
.github/push-hook-sample.json
vendored
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"ref": "refs/heads/edge"
|
||||
}
|
||||
@@ -1,14 +1,4 @@
|
||||
name: Publish Docker image to registries
|
||||
|
||||
# Builds image and tags based on the type of push event:
|
||||
# * branch push -> tag is branch name IE context-mod:edge
|
||||
# * release (tag) -> tag is release name IE context-mod:0.13.0
|
||||
#
|
||||
# Then pushes tagged images to multiple registries
|
||||
#
|
||||
# Based on
|
||||
# https://github.com/docker/build-push-action/blob/master/docs/advanced/push-multi-registries.md
|
||||
# https://github.com/docker/metadata-action
|
||||
name: Publish Docker image to Dockerhub
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -23,12 +13,8 @@ on:
|
||||
|
||||
jobs:
|
||||
push_to_registry:
|
||||
name: Build and Push Docker image to registries
|
||||
name: Push Docker image to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
# https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v2
|
||||
@@ -39,22 +25,12 @@ jobs:
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v3
|
||||
with:
|
||||
images: |
|
||||
foxxmd/context-mod
|
||||
ghcr.io/foxxmd/context-mod
|
||||
images: foxxmd/context-mod
|
||||
# generate Docker tags based on the following events/attributes
|
||||
tags: |
|
||||
type=raw,value=latest,enable=${{ endsWith(github.ref, 'master') }}
|
||||
@@ -64,8 +40,7 @@ jobs:
|
||||
latest=false
|
||||
|
||||
- name: Build and push Docker image
|
||||
if: ${{ !env.ACT }}
|
||||
uses: docker/build-push-action@v3
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
2
.gitignore
vendored
@@ -336,7 +336,6 @@ web_modules/
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
.env.test
|
||||
*.env
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
@@ -392,7 +391,6 @@ dist
|
||||
*.json5
|
||||
|
||||
!src/Schema/*.json
|
||||
!.github/push-hook-sample.json
|
||||
!docs/**/*.json5
|
||||
!docs/**/*.yaml
|
||||
!docs/**/*.json
|
||||
|
||||
12
Dockerfile
@@ -81,8 +81,9 @@ RUN apk add --no-cache \
|
||||
#
|
||||
|
||||
# vips required to run sharp library for image comparison
|
||||
# opencv required for other image processing
|
||||
RUN echo "http://dl-4.alpinelinux.org/alpine/v3.14/community" >> /etc/apk/repositories \
|
||||
&& apk --no-cache add vips
|
||||
&& apk --no-cache add vips opencv opencv-dev
|
||||
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
|
||||
@@ -115,6 +116,15 @@ RUN npm install --production \
|
||||
&& rm -rf node_modules/ts-node \
|
||||
&& rm -rf node_modules/typescript
|
||||
|
||||
# build bindings for opencv
|
||||
RUN apk add --no-cache --virtual .build-deps \
|
||||
make \
|
||||
g++ \
|
||||
gcc \
|
||||
libgcc \
|
||||
&& npm run cv-install-docker-prebuild \
|
||||
&& apk del .build-deps
|
||||
|
||||
ENV NPM_CONFIG_LOGLEVEL debug
|
||||
|
||||
# can set database to use more performant better-sqlite3 since we control everything
|
||||
|
||||
@@ -31,8 +31,6 @@ Feature Highlights for **Moderators:**
|
||||
* [**Web interface**](#web-ui-and-screenshots) for monitoring, administration, and oauth bot authentication
|
||||
* [**Placeholders**](/docs/subreddit/actionTemplating.md) (like automoderator) can be configured via a wiki page or raw text and supports [mustache](https://mustache.github.io) templating
|
||||
* [**Partial Configurations**](/docs/subreddit/components/README.md#partial-configurations) -- offload parts of your configuration to shared locations to consolidate logic between multiple subreddits
|
||||
* [Guest Access](/docs/subreddit/README.md#guest-access) enables collaboration and easier setup by allowing temporary access
|
||||
* [Toxic content prediction](/docs/subreddit/components/README.md#moderatehatespeechcom-predictions) using [moderatehatespeech.com](https://moderatehatespeech.com) machine learning model
|
||||
|
||||
Feature highlights for **Developers and Hosting (Operators):**
|
||||
|
||||
@@ -136,10 +134,6 @@ Moderator view/invite and authorization:
|
||||
|
||||

|
||||
|
||||
A similar helper and invitation experience is available for adding **subreddits to an existing bot.**
|
||||
|
||||

|
||||
|
||||
### Configuration Editor
|
||||
|
||||
A built-in editor using [monaco-editor](https://microsoft.github.io/monaco-editor/) makes editing configurations easy:
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
GITHUB_TOKEN=
|
||||
DOCKERHUB_USERNAME=
|
||||
DOCKER_PASSWORD=
|
||||
@@ -152,8 +152,7 @@ An **Action** is some action the bot can take against the checked Activity (comm
|
||||
|
||||
* For **Operator/Bot maintainers** see **[Operation Guide](/docs/operator/README.md)**
|
||||
* For **Moderators**
|
||||
* Start with the [Subreddit/Moderator docs](/docs/subreddit/README.md) or [Moderator Getting Started guide](/docs/subreddit/gettingStarted.md)
|
||||
* Refer to the [Subreddit Components Documentation](/docs/subreddit/components) or the [subreddit-ready examples](/docs/subreddit/components/cookbook)
|
||||
* Refer to the [Subreddit Components Documentation](/docs/subreddit/components) or the [subreddit-ready examples](/docs/subreddit/components/subredditReady)
|
||||
* as well as the [schema](https://json-schema.app/view/%23?url=https%3A%2F%2Fraw.githubusercontent.com%2FFoxxMD%2Fcontext-mod%2Fmaster%2Fsrc%2FSchema%2FApp.json) which has
|
||||
* fully annotated configuration data/structure
|
||||
* generated examples in json/yaml
|
||||
|
||||
@@ -1,17 +1,5 @@
|
||||
TODO add more development sections...
|
||||
|
||||
# Developing/Testing Github Actions
|
||||
|
||||
Use [act](https://github.com/nektos/act) to run Github actions locally.
|
||||
|
||||
An example secrets file can be found in the project working directory at [act.env.example](act.env.example)
|
||||
|
||||
Modify [push-hook-sample.json](.github/push-hook-sample.json) to point to the local branch you want to run a `push` event trigger on, then run this command from the project working directory:
|
||||
|
||||
```bash
|
||||
act -e .github/push-hook-sample.json --secret-file act.env
|
||||
```
|
||||
|
||||
# Mocking Reddit API
|
||||
|
||||
Using [MockServer](https://www.mock-server.com/)
|
||||
|
||||
|
Before Width: | Height: | Size: 133 KiB After Width: | Height: | Size: 125 KiB |
|
Before Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 137 KiB After Width: | Height: | Size: 148 KiB |
|
Before Width: | Height: | Size: 158 KiB After Width: | Height: | Size: 226 KiB |
|
Before Width: | Height: | Size: 141 KiB |
|
Before Width: | Height: | Size: 225 KiB After Width: | Height: | Size: 479 KiB |
@@ -95,7 +95,7 @@ The Retention Policy can be specified at operator level, bot, subreddit *overrid
|
||||
operator:
|
||||
name: u/MyRedditAccount
|
||||
databaseConfig:
|
||||
retention: '3 months' # each subreddit will retain 3 months of recorded events
|
||||
retention: '3 months' # each subreddit will retain 3 more of recorded events
|
||||
bots:
|
||||
# all subreddits this bot moderates will have 3 month retention
|
||||
- name: u/OneBotAccount
|
||||
|
||||
@@ -8,10 +8,7 @@ ContextMod can be run on almost any operating system but it is recommended to us
|
||||
|
||||
PROTIP: Using a container management tool like [Portainer.io CE](https://www.portainer.io/products/community-edition) will help with setup/configuration tremendously.
|
||||
|
||||
Images available from these registeries:
|
||||
|
||||
* [Dockerhub](https://hub.docker.com/r/foxxmd/context-mod) - `docker.io/foxxmd/context-mod`
|
||||
* [GHCR](https://github.com/foxxmd/context-mod/pkgs/container/context-mod) - `ghcr.io/foxxmd/context-mod`
|
||||
### [Dockerhub](https://hub.docker.com/r/foxxmd/context-mod)
|
||||
|
||||
An example of starting the container using the [minimum configuration](/docs/operator/configuration.md#minimum-config):
|
||||
|
||||
@@ -20,7 +17,7 @@ An example of starting the container using the [minimum configuration](/docs/ope
|
||||
* Expose the web interface using the container port `8085`
|
||||
|
||||
```
|
||||
docker run -d -v /host/path/folder:/config -p 8085:8085 ghcr.io/foxxmd/context-mod:latest
|
||||
docker run -d -v /host/path/folder:/config -p 8085:8085 foxxmd/context-mod
|
||||
```
|
||||
|
||||
The location of `DATA_DIR` in the container can be changed by passing it as an environmental variable EX `-e "DATA_DIR=/home/abc/config`
|
||||
@@ -37,7 +34,7 @@ To get the UID and GID for the current user run these commands from a terminal:
|
||||
* `id -g` -- prints GID
|
||||
|
||||
```
|
||||
docker run -d -v /host/path/folder:/config -p 8085:8085 -e PUID=1000 -e PGID=1000 ghcr.io/foxxmd/context-mod:latest
|
||||
docker run -d -v /host/path/folder:/config -p 8085:8085 -e PUID=1000 -e PGID=1000 foxxmd/context-mod
|
||||
```
|
||||
|
||||
## Locally
|
||||
@@ -63,6 +60,65 @@ An example of running CM using the [minimum configuration](/docs/operator/config
|
||||
node src/index.js run
|
||||
```
|
||||
|
||||
### Dependencies
|
||||
|
||||
Note: All below dependencies are automatically included in the [Docker](#docker-recommended) image.
|
||||
|
||||
#### Sharp
|
||||
|
||||
For basic [Image Comparisons](/docs/imageComparison.md) and image data CM uses [sharp](https://sharp.pixelplumbing.com/) which depends on [libvips](https://www.libvips.org/)
|
||||
|
||||
Binaries for Sharp and libvips ship with the `sharp` npm package for all major operating systems and should require no additional steps to use -- installing CM with the above script should be sufficient.
|
||||
|
||||
See more about Sharp dependencies in the [image comparison prerequisites.](/docs/imageComparison.md#prerequisites)
|
||||
|
||||
|
||||
#### OpenCV
|
||||
|
||||
For advanced image comparison CM uses [OpenCV.](https://opencv.org/) OpenCV is an **optional** dependency that is only utilized if CM is configured to run these advanced image operations so if you are NOT doing any image-related operations you can safely ignore this section/dependency.
|
||||
|
||||
**NOTE:** Depending on the image being compared (resolution) and operations being performed this can be a **CPU heavy resource.** TODO: Add rules that are cpu heavy...
|
||||
|
||||
##### Installation
|
||||
|
||||
Installation is not an automatic process. The below instructions are a summary of "easy" paths for installation but are not exhaustive. DO reference the detailed instructions (including additional details for windows installs) at [opencv4nodejs How to Install](https://github.com/UrielCh/opencv4nodejs#how-to-install).
|
||||
|
||||
###### Build From Source
|
||||
|
||||
This may take **some time** since openCV will be built from scratch.
|
||||
|
||||
On windows you must first install build tools: `npm install --global windows-build-tools`
|
||||
|
||||
Otherwise, run one of the following commands from the CM project directory:
|
||||
|
||||
* For CUDA (Nvidia GPU acceleration): `npm run cv-autoinstall-cuda`
|
||||
* Normal: `npm run cv-autoinstall`
|
||||
|
||||
###### Build from Prebuilt
|
||||
|
||||
In this use-case you already have openCV built OR are using a distro prebuilt package. This method is much faster than building from source as only bindings need to be built.
|
||||
|
||||
[More information on prebuild installation](https://github.com/UrielCh/opencv4nodejs#installing-opencv-manually)
|
||||
|
||||
Prerequisites:
|
||||
|
||||
* Windows `choco install OpenCV -y -version 4.1.0`
|
||||
* MacOS `brew install opencv@4; brew link --force opencv@4`
|
||||
* Linux -- varies, check your package manager for `opencv` and `opencv-dev`
|
||||
|
||||
A script for building on **Ubuntu** is already included in CM:
|
||||
|
||||
* `sudo apt install opencv-dev`
|
||||
* `npm run cv-install-ubuntu-prebuild`
|
||||
|
||||
Otherwise, you will need to modify `scripts` in CM's `package.json`, use the script `cv-install-ubuntu-prebuild` as an example. Your command must include:
|
||||
|
||||
* `--incDir [path/to/opencv/dev-files]` (on linux, usually `/usr/include/opencv4/`)
|
||||
* `--libDir [path/to/opencv/shared-files]` (on linux usually `/lib/x86_64-linux-gnu/` or `/usr/lib/`)
|
||||
* `--binDir=[path/to/openv/binaries]` (on linux usually `/usr/bin/`)
|
||||
|
||||
After you have modified/added a script for your operating system run it with `npm run yourScriptName`
|
||||
|
||||
## [Heroku Quick Deploy](https://heroku.com/about)
|
||||
|
||||
**NOTE:** This is still experimental and requires more testing.
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
This section is for **reddit moderators**. It covers how to use a CM bot for your subreddit.
|
||||
|
||||
If you are trying to run a ContextMod instance (the actual software) please refer to the [operator section](/docs/operator/README.md).
|
||||
|
||||
# Table of Contents
|
||||
|
||||
* [Overview](#overview)
|
||||
* [Your Relationship to CM](#your-relationship-to-cm)
|
||||
* [Operator](#operator)
|
||||
* [Your Bot](#your-bot)
|
||||
* [Getting Started](#getting-started)
|
||||
* [Accessing The Bot](#accessing-the-bot)
|
||||
* [Editing The Bot](#editing-the-bot)
|
||||
* [Configuration](#configuration)
|
||||
* [Guest Access](#guest-access)
|
||||
|
||||
# Overview
|
||||
|
||||
The Context Mod **software** can manage multiple **bots** (reddit accounts used as bots, like `/u/MyCMBot`). Each bot can manage (run) multiple **subreddits** which is determined by the subreddits the account is a moderator of.
|
||||
|
||||
You, the moderator of a subreddit a CM bot runs in, can access/manage the Bot using the CM software's [web interface](/docs/images/subredditStatus.jpg) and control its behavior using the [web editor.](/docs/images/editor.jpg)
|
||||
|
||||
## Your Relationship to CM
|
||||
|
||||
It is important to understand the relationship between you (the moderator), the bot, and the operator (the person running the CM software).
|
||||
|
||||
The easiest way to think about this is in relation to how you use Automoderator and interact with Reddit as a moderator. As an analogy:
|
||||
|
||||
### Operator
|
||||
|
||||
The operator is the person running the actual server/machine the Context Mod software is on.
|
||||
|
||||
They are best thought of as **Reddit:**
|
||||
|
||||
* Mostly hands-off when it comes to the bot and interacting with your subreddit
|
||||
* You must interact with Reddit first before you can use automoderator (login, create a subreddit, etc...)
|
||||
|
||||
Unlike reddit, though, there is a greater level of trust required between you and the Operator because what you make the Bot do ultimately affects the Operator since they are the ones actually running your Bot and making API calls to reddit.
|
||||
|
||||
### Your Bot
|
||||
|
||||
Your bot is like an **invite-only version of Automoderator**:
|
||||
|
||||
* Unlike automoderator, you **must** interact with the Operator in order to get the bot working. It is not public for anyone to use.
|
||||
* Like automoderator, you **must** create a [configuration](/docs/subreddit/components/README.md) for it do anything.
|
||||
* The bot does not come pre-configured for you. It is a blank slate and requires user input to be useful.
|
||||
* Also like automoderator, you are **entirely in control of the bot.**
|
||||
* You can start, stop, and edit its behavior at any time without needing to communicate with the Operator.
|
||||
* CM provides you _tools_, different ways the Bot can detect patterns in your subreddit/users as well as actions it can, and you can decide to use them however you want.
|
||||
* Your bot is **only accessible to moderators of your subreddit.**
|
||||
|
||||
# Getting Started
|
||||
|
||||
The [Getting Started](/docs/subreddit/gettingStarted.md) guide lays out the steps needed to go from nothing to a working Bot. If you are a moderator new to Context Mod this is where you want to begin.
|
||||
|
||||
# Accessing The Bot
|
||||
|
||||
All bot management and editing is done through the [web interface.](/docs/images/subredditStatus.jpg) The URL used for accessing this interface is given to you by the **Operator** once they have agreed to host your bot/subreddit.
|
||||
|
||||
NOTE: This interface is **only access to moderators of your subreddit** and [guests.](#guest-access) You must login to the web interface **with your moderator account** in order to access it.
|
||||
|
||||
A **guided tour** that helps show how to manage the bot at a high-level is available on the web interface by clicking the **Help** button in the top-right of the page.
|
||||
|
||||
## Editing The Bot
|
||||
|
||||
Find the [editor in the web interface](/docs/webInterface.md#editingupdating-your-config) to access the built-in editor for the bot.
|
||||
|
||||
[The editor](/docs/images/editor.jpg) should be your all-in-one location for viewing and editing your bot's behavior. **It is equivalent to Automoderator's editor page.**
|
||||
|
||||
The editor features:
|
||||
|
||||
* syntax validation and highlighting
|
||||
* configuration auto-complete and documentation (hover over properties)
|
||||
* built-in validation using Microsoft Word "squiggly lines" indicators and an error list at the bottom of the window
|
||||
* built-in saving (at the top of the window)
|
||||
|
||||
# Configuration
|
||||
|
||||
Use the [Configuration Reference](/docs/subreddit/components/README.md) to learn about all the different components available for building a CM configuration.
|
||||
|
||||
Additionally, refer to [How It Works](/docs/README.md#how-it-works) and [Core Concepts](/docs/README.md#concepts) to learn the basic of CM configuration.
|
||||
|
||||
After you have the basics under your belt you could use the [subreddit configurations cookbook](/docs/subreddit/components/cookbook) to familiarize yourself with a complete configuration and ways to use CM.
|
||||
|
||||
# Guest Access
|
||||
|
||||
CM supports **Guest Access**. Reddit users who are given Guest Access to your bot are allowed to access the web interface even though they are not moderators.
|
||||
|
||||
Additionally, they can edit the subreddit's config using the bot. If a Guest edits your config their username will be mentioned in the wiki page edit reason.
|
||||
|
||||
Guests can do everything a regular mod can except view/add/remove Guest. They can be removed at any time or set with an expiration date that their access is removed on.
|
||||
|
||||
**Guests are helpful if you are new to CM and know reddit users that can help you get started.**
|
||||
|
||||
[Add guests from the Subreddit tab in the main interface.](/docs/images/guests.jpg)
|
||||
@@ -1,32 +1,12 @@
|
||||
Actions that can submit text (Report, Comment, UserNote, Message, Ban, Submission) will have their `content` values run through a [Mustache Template](https://mustache.github.io/). This means you can insert data generated by Rules into your text before the Action is performed.
|
||||
Actions that can submit text (Report, Comment, UserNote) will have their `content` values run through a [Mustache Template](https://mustache.github.io/). This means you can insert data generated by Rules into your text before the Action is performed.
|
||||
|
||||
See here for a [cheatsheet](https://gist.github.com/FoxxMD/d365707cf99fdb526a504b8b833a5b78) and [here](https://www.tsmean.com/articles/mustache/the-ultimate-mustache-tutorial/) for a more thorough tutorial.
|
||||
|
||||
# Template Data
|
||||
|
||||
Some data can always be accessed at the top-level. Example
|
||||
|
||||
```
|
||||
This action was run from {{manager}} in Check {{check}}.
|
||||
|
||||
The bot intro post is {{botLink}}
|
||||
|
||||
Message the moderators of this subreddit using this [compose link]({{modmailLink}})
|
||||
```
|
||||
|
||||
|
||||
|
||||
| Name | Description | Example |
|
||||
|---------------|---------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `manager` | The name of the subreddit the bot is running in | mealtimevideos |
|
||||
| `check` | The name of the Check that was triggered | myCheck |
|
||||
| `botLink` | A link to the bot introduction | https://www.reddit.com/r/ContextModBot/comments/otz396/introduction_to_contextmodbot |
|
||||
| `modmailLink` | A link that opens reddit's DM compose with the subject line as the Activity being processed | https://www.reddit.com/message/compose?to=/r/mealtimevideos&message=https://www.reddit.com/r/ContextModBot/comments/otz396/introduction_to_contextmodbot |
|
||||
|
||||
|
||||
## Activity Data
|
||||
|
||||
**Activity data can be accessed using the `item` variable.** Example
|
||||
Activity data can be accessed using the `item` variable. Example
|
||||
|
||||
```
|
||||
This activity is a {{item.kind}} with {{item.votes}} votes, created {{item.age}} ago.
|
||||
@@ -39,17 +19,14 @@ Produces:
|
||||
|
||||
All Actions with `content` have access to this data:
|
||||
|
||||
| Name | Description | Example |
|
||||
|--------------|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------|
|
||||
| `kind` | The Activity type (submission or comment) | submission |
|
||||
| `author` | Name of the Author of the Activity being processed | FoxxMD |
|
||||
| `permalink` | URL to the Activity | https://reddit.com/r/mySuibreddit/comments/ab23f/my_post |
|
||||
| `votes` | Number of upvotes | 69 |
|
||||
| `age` | The age of the Activity in a [human friendly format](https://day.js.org/docs/en/durations/humanize) | 5 minutes |
|
||||
| `subreddit` | The name of the subreddit the Activity is from | mealtimevideos |
|
||||
| `id` | The `Reddit Thing` ID for the Activity | t3_0tin1 |
|
||||
| `title` | As comments => the body of the comment. As Submission => title | Test post please ignore |
|
||||
| `shortTitle` | The same as `title` but truncated to 15 characters | test post pleas... |
|
||||
| Name | Description | Example |
|
||||
|-------------|-----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
|
||||
| `kind` | The Activity type (submission or comment) | submission |
|
||||
| `author` | Name of the Author of the Activity being processed | FoxxMD |
|
||||
| `permalink` | URL to the Activity | https://reddit.com/r/mySuibreddit/comments/ab23f/my_post |
|
||||
| `votes` | Number of upvotes | 69 |
|
||||
| `age` | The age of the Activity in a [human friendly format](https://day.js.org/docs/en/durations/humanize) | 5 minutes |
|
||||
| `botLink` | A URL to CM's introduction thread | https://www.reddit.com/r/ContextModBot/comments/otz396/introduction_to_contextmodbot |
|
||||
|
||||
### Submissions
|
||||
|
||||
@@ -112,39 +89,7 @@ Produces
|
||||
|
||||
> Submission was repeated 7 times
|
||||
|
||||
## Action Data
|
||||
|
||||
### Summary
|
||||
|
||||
A summary of what actions have already been run **when the template is rendered** is available using the `actionSummary` variable. It is therefore important that the Action you want to produce the summary is run **after** any other Actions you want to get a summary for.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
A summary of actions processed for this activity, so far:
|
||||
|
||||
{{actionSummary}}
|
||||
```
|
||||
|
||||
Would produce:
|
||||
> A summary of actions processed for this activity, so far:
|
||||
>
|
||||
> * approve - ✘ - Item is already approved??
|
||||
> * lock - ✓
|
||||
> * modnote - ✓ - (SOLID_CONTRIBUTOR) User is good
|
||||
|
||||
### Individual
|
||||
|
||||
Individual **Actions** can be accessed using the name of the action, **lower-cased, with all spaces/dashes/underscores.** Example:
|
||||
|
||||
```
|
||||
User was banned for {{actions.exampleban.duration}} for {{actions.exampleban.reason}}
|
||||
```
|
||||
Produces
|
||||
|
||||
> User was banned for 4 days for toxic behavior
|
||||
|
||||
# Quick Templating Tutorial
|
||||
#### Quick Templating Tutorial
|
||||
|
||||
As a quick example for how you will most likely be using templating -- wrapping a variable in curly brackets, `{{variable}}`, will cause the variable value to be rendered instead of the brackets:
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ This list is not exhaustive. [For complete documentation on a subreddit's config
|
||||
* [Regex](#regex)
|
||||
* [Repost](#repost)
|
||||
* [Sentiment Analysis](#sentiment-analysis)
|
||||
* [Toxic Content Prediction](#moderatehatespeechcom-predictions)
|
||||
* [Rule Sets](#rule-sets)
|
||||
* [Actions](#actions)
|
||||
* [Named Actions](#named-actions)
|
||||
@@ -70,7 +69,6 @@ This list is not exhaustive. [For complete documentation on a subreddit's config
|
||||
* [Rule Order](#rule-order)
|
||||
* [Configuration Re-use and Caching](#configuration-re-use-and-caching)
|
||||
* [Partial Configurations](#partial-configurations)
|
||||
* [Sharing Configs Between Subreddits](#sharing-full-configs-as-runs)
|
||||
* [Subreddit-ready examples](#subreddit-ready-examples)
|
||||
|
||||
# Runs
|
||||
@@ -379,12 +377,6 @@ This rule is for searching **all of Reddit** for reposts, as opposed to just the
|
||||
|
||||
The **Sentiment Rule** is used to determine the overall emotional intent (negative, neutral, positive) of a Submission or Comment by analyzing the actual text content of the Activity.
|
||||
|
||||
### ModerateHateSpeech.com Predictions
|
||||
|
||||
[**Full Documentation**](/docs/subreddit/components/mhs)
|
||||
|
||||
ContextMod integrates with [moderatehatespeech.com](https://moderatehatespeech.com/) (MHS) [toxic content machine learning model](https://moderatehatespeech.com/framework/) through their API. This rule sends an Activity's content (title or body) to MHS which returns a prediction on whether the content is toxic and actionable by a moderator. Their model is [specifically trained for reddit content.](https://www.reddit.com/r/redditdev/comments/xdscbo/updated_bot_backed_by_moderationoriented_ml_for/)
|
||||
|
||||
# Rule Sets
|
||||
|
||||
The `rules` list on a `Check` can contain both `Rule` objects and `RuleSet` objects.
|
||||
@@ -537,25 +529,6 @@ actions:
|
||||
targets: string # 'self' or 'parent' or 'https://reddit.com/r/someSubreddit/21nfdi....'
|
||||
```
|
||||
|
||||
### Comment As Subreddit
|
||||
|
||||
ContextMod can comment [as the subreddit](https://www.reddit.com/r/modnews/comments/wpy5c8/announcing_remove_as_a_subreddit/) using the `/u/subreddit-ModTeam` account with some restrictions:
|
||||
|
||||
* The activity being replied to must ALREADY BE REMOVED.
|
||||
* You can use the [Remove Action](#remove) beforehand to ensure this is the case.
|
||||
* The created comment will always be stickied and distinguished
|
||||
|
||||
Usage:
|
||||
|
||||
```yaml
|
||||
actions:
|
||||
- kind: comment
|
||||
asModTeam: true
|
||||
content: string # required, the content of the comment
|
||||
lock: boolean # lock the comment after creation
|
||||
targets: string # 'self' or 'parent' or 'https://reddit.com/r/someSubreddit/21nfdi....'
|
||||
```
|
||||
|
||||
### Submission
|
||||
|
||||
Create a Submission [Schema Documentation](https://json-schema.app/view/%23/%23%2Fdefinitions%2FSubmissionCheckJson/%23%2Fdefinitions%2FSubmissionActionJson?url=https%3A%2F%2Fraw.githubusercontent.com%2FFoxxMD%2Freddit-context-bot%2Fmaster%2Fsrc%2FSchema%2FApp.json)
|
||||
@@ -719,16 +692,15 @@ Some other things to note:
|
||||
* If the `to` property is not specified then the message is sent to the Author of the Activity being processed
|
||||
* `to` may be a **User** (u/aUser) or a **Subreddit** (r/aSubreddit)
|
||||
* `to` **cannot** be a Subreddit when `asSubreddit: true` -- IE cannot send subreddit-to-subreddit messages
|
||||
* TIP: `to` can be templated -- to send a message to the subreddit the Activity being processed is in use `'r/{{item.subreddit}}'`
|
||||
* `content` and `title` can be [templated](#templating) and use [URL Tokens](#url-tokens)
|
||||
* `content` can be [templated](#templating) and use [URL Tokens](#url-tokens)
|
||||
|
||||
```yaml
|
||||
actions:
|
||||
- kind: message
|
||||
asSubreddit: true
|
||||
content: 'A message sent as the subreddit' # can be templated
|
||||
title: 'Title of the message' # can be templated
|
||||
to: 'u/aUser' # do not specify 'to' in order default to sending to Author of Activity being processed. Can also be templated
|
||||
content: 'A message sent as the subreddit'
|
||||
title: 'Title of the message'
|
||||
to: 'u/aUser' # do not specify 'to' in order default to sending to Author of Activity being processed
|
||||
```
|
||||
|
||||
### Remove
|
||||
@@ -774,7 +746,7 @@ actions:
|
||||
- kind: usernote
|
||||
type: spamwarn
|
||||
content: 'Usernote message'
|
||||
existingNoteCheck: boolean # if true (default) then the usernote will not be added if the same note appears for this activity
|
||||
allowDuplicate: boolean # if false then the usernote will not be added if the same note appears for this activity
|
||||
```
|
||||
|
||||
### Mod Note
|
||||
@@ -799,7 +771,6 @@ actions:
|
||||
type: SPAM_WATCH
|
||||
content: 'a note only mods can see message' # optional
|
||||
referenceActivity: boolean # if true the Note will be linked to the Activity being processed
|
||||
existingNoteCheck: boolean # if true (default) then the note will not be added if the same note appears for this activity
|
||||
```
|
||||
|
||||
# Filters
|
||||
@@ -1267,49 +1238,6 @@ The object contains:
|
||||
* `path` -- REQUIRED string following rules above
|
||||
* `ttl` -- OPTIONAL, number of seconds to cache the URL result. Defaults to `WikiTTL`
|
||||
|
||||
### Sharing Full Configs as Runs
|
||||
|
||||
If the Fragment fetched by CM is a "full config" (including `runs`, `polling`, etc...) that could be used as a valid config for another subreddit then CM will extract and use the **Runs** from that config.
|
||||
|
||||
**However, the config must also explicitly allow access for use as a Fragment.** This is to prevent subreddits that share a Bot account from accidentally (or intentionally) gaining access to another subreddit's config with permissions.
|
||||
|
||||
#### Sharing
|
||||
|
||||
The config that will be shared (accessed at `wiki:botconfig/contextbot|SharingSubreddit`) must have the `sharing` property defined at its top-level. If `sharing` is not defined access will be denied for all subreddits.
|
||||
|
||||
```yaml
|
||||
sharing: false # deny access to all subreddits (default when sharing is not defined)
|
||||
|
||||
polling:
|
||||
- newComm
|
||||
|
||||
runs:
|
||||
# ...
|
||||
```
|
||||
|
||||
```yaml
|
||||
sharing: true # any subreddit can use this config (reddit account must also be able to access wiki page)
|
||||
```
|
||||
|
||||
```yaml
|
||||
# when a list is given all subreddit names that match any from the list are ALLOWED to access the config
|
||||
# list can be regular expressions or case-insensitive strings
|
||||
sharing:
|
||||
- mealtimevideos
|
||||
- videos
|
||||
- '/Ask.*/i'
|
||||
```
|
||||
|
||||
```yaml
|
||||
# if `exclude` is used then any subreddit name that is NOT on this list can access the config
|
||||
# list can be regular expressions or case-insensitive strings
|
||||
sharing:
|
||||
exclude:
|
||||
- mealtimevideos
|
||||
- videos
|
||||
- '/Ask.*/i'
|
||||
```
|
||||
|
||||
#### Examples
|
||||
|
||||
**Replacing A Rule with a URL Fragment**
|
||||
@@ -1332,7 +1260,7 @@ runs:
|
||||
subreddits:
|
||||
- MyBadSubreddit
|
||||
window: 7 days
|
||||
actions:
|
||||
actions:
|
||||
- kind: report
|
||||
content: 'uses freekarma subreddits and bad subreddits'
|
||||
```
|
||||
@@ -1367,33 +1295,6 @@ runs:
|
||||
content: 'uses freekarma subreddits'
|
||||
```
|
||||
|
||||
**Using Another Subreddit's Config**
|
||||
|
||||
```yaml
|
||||
runs:
|
||||
- `wiki:botconfig/contextbot|SharingSubreddit`
|
||||
- name: MySubredditSpecificRun
|
||||
checks:
|
||||
- name: Free Karma Alert
|
||||
description: Check if author has posted in 'freekarma' subreddits
|
||||
kind: submission
|
||||
rules:
|
||||
- 'wiki:freeKarmaFrag'
|
||||
actions:
|
||||
- kind: report
|
||||
content: 'uses freekarma subreddits'
|
||||
```
|
||||
|
||||
In `r/SharingSubreddit`:
|
||||
|
||||
```yaml
|
||||
sharing: true
|
||||
|
||||
runs:
|
||||
- name: ARun
|
||||
# ...
|
||||
```
|
||||
|
||||
# Subreddit-Ready Examples
|
||||
|
||||
Refer to the [Subreddit Cookbook Examples](/docs/subreddit/components/cookbook) section to find ready-to-use configurations for common scenarios (spam, freekarma blocking, etc...). This is also a good place to familiarize yourself with what complete configurations look like.
|
||||
Refer to the [Subreddit-Ready Examples](/docs/subreddit/components/subredditReady) section to find ready-to-use configurations for common scenarios (spam, freekarma blocking, etc...). This is also a good place to familiarize yourself with what complete configurations look like.
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
// if the nested rules pass the condition then the Rule Set triggers the Check
|
||||
//
|
||||
// AND = all nested rules must be triggered to make the Rule Set trigger
|
||||
// OR = any of the nested Rules will be the Rule Set trigger
|
||||
// AND = any of the nested Rules will be the Rule Set trigger
|
||||
"condition": "AND",
|
||||
// in this check we use an Attribution >10% on ONLY submissions, which is a lower requirement then the above attribution rule
|
||||
// and combine it with a History rule looking for low comment engagement
|
||||
|
||||
@@ -22,7 +22,7 @@ runs:
|
||||
# if the nested rules pass the condition then the Rule Set triggers the Check
|
||||
#
|
||||
# AND = all nested rules must be triggered to make the Rule Set trigger
|
||||
# OR = any of the nested Rules will be the Rule Set trigger
|
||||
# AND = any of the nested Rules will be the Rule Set trigger
|
||||
- condition: AND
|
||||
# in this check we use an Attribution >10% on ONLY submissions, which is a lower requirement then the above attribution rule
|
||||
# and combine it with a History rule looking for low comment engagement
|
||||
|
||||
@@ -8,24 +8,7 @@ The **Attribution** rule will aggregate an Author's content Attribution (youtube
|
||||
|
||||
Consult the [schema](https://json-schema.app/view/%23/%23%2Fdefinitions%2FCheckJson/%23%2Fdefinitions%2FAttributionJSONConfig?url=https%3A%2F%2Fraw.githubusercontent.com%2FFoxxMD%2Fcontext-mod%2Fmaster%2Fsrc%2FSchema%2FApp.json) for a complete reference of the rule's properties.
|
||||
|
||||
# [Template Variables](/docs/subreddit/actionTemplating.md)
|
||||
### Examples
|
||||
|
||||
| Name | Description | Example |
|
||||
|------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|
|
||||
| `result` | Summary of rule results (also found in Actioned Events) | 1 Attribution(s) met the threshold of >= 20%, with 6 (40%) of 15 Total -- window: 3 years |
|
||||
| `triggeredDomainCount` | Number of domains that met the threshold | 1 |
|
||||
| `window` | Number or duration of Activities considered from window | 3 years |
|
||||
| `largestCount` | The count from the largest aggregated domain | 6 |
|
||||
| `largestPercentage` | The percentage of Activities the largest aggregated domain comprises | 40% |
|
||||
| `smallestCount` | The count from the smallest aggregated domain | 1 |
|
||||
| `smallestPercentage` | The percentage of Activities the smallest aggregated domain comprises | 6% |
|
||||
| `countRange` | A convenience string displaying "smallestCount - largestCount" or just one number if both are the same | 5 |
|
||||
| `percentRange` | A convenience string displaying "smallestPercentage - largestPercentage" or just one percentage if both are the same | 34% |
|
||||
| `domainsDelim` | A comma-delimited list of all the domain URLs that met the threshold | youtube.com/example1, youtube.com/example2, rueters.com |
|
||||
| `titlesDelim` | A comma-delimited list of friendly-names of the domain if one is present, otherwise the URL (IE youtube.com/c/34ldfa343 => "My Youtube Channel Title") | My Channel A, My Channel B, reuters.com |
|
||||
| `threshold` | The threshold you configured for this Rule to trigger | `>= 20%` |
|
||||
|
||||
# Examples
|
||||
|
||||
* Self Promotion as percentage of all Activities [YAML](/docs/subreddit/components/attribution/redditSelfPromoAll.yaml) | [JSON](/docs/subreddit/components/attribution/redditSelfPromoAll.json5) - Check if Author is submitting much more than they comment.
|
||||
* Self Promotion as percentage of all Activities [YAML](/docs/subreddit/componentscomponents/attribution/redditSelfPromoAll.yaml) | [JSON](/docs/subreddit/componentscomponents/attribution/redditSelfPromoAll.json5) - Check if Author is submitting much more than they comment.
|
||||
* Self Promotion as percentage of Submissions [YAML](/docs/subreddit/components/attribution/redditSelfPromoSubmissionsOnly.yaml) | [JSON](/docs/examplesm/attribution/redditSelfPromoSubmissionsOnly.json5) - Check if any of Author's aggregated submission origins are >10% of their submissions
|
||||
|
||||
@@ -9,7 +9,7 @@ The **Author** rule triggers if any [AuthorCriteria](https://json-schema.app/vie
|
||||
* author's subreddit flair text
|
||||
* author's subreddit flair css
|
||||
* author's subreddit mod status
|
||||
* [Toolbox User Notes](/docs/subreddit/components/userNotes)
|
||||
* [Toolbox User Notes](/docs/subreddit/componentscomponents/userNotes)
|
||||
|
||||
The Author **Rule** is best used in conjunction with other Rules to short-circuit a Check based on who the Author is. It is easier to use a Rule to do this then to write **author filters** for every Rule (and makes Rules more re-useable).
|
||||
|
||||
@@ -18,10 +18,10 @@ Consult the [schema](https://json-schema.app/view/%23%2Fdefinitions%2FAuthorRule
|
||||
### Examples
|
||||
|
||||
* Basic examples
|
||||
* Flair new user Submission [YAML](/docs/subreddit/components/author/flairNewUserSubmission.yaml) | [JSON](/docs/subreddit/components/author/flairNewUserSubmission.json5) - If the Author does not have the `vet` flair then flair the Submission with `New User`
|
||||
* Flair vetted user Submission [YAML](/docs/subreddit/components/author/flairNewUserSubmission.yaml) | [JSON](/docs/subreddit/components/author/flairNewUserSubmission.json5) - If the Author does have the `vet` flair then flair the Submission with `Vetted`
|
||||
* Flair new user Submission [YAML](/docs/subreddit/componentscomponents/author/flairNewUserSubmission.yaml) | [JSON](/docs/subreddit/componentscomponents/author/flairNewUserSubmission.json5) - If the Author does not have the `vet` flair then flair the Submission with `New User`
|
||||
* Flair vetted user Submission [YAML](/docs/subreddit/componentscomponents/author/flairNewUserSubmission.yaml) | [JSON](/docs/subreddit/componentscomponents/author/flairNewUserSubmission.json5) - If the Author does have the `vet` flair then flair the Submission with `Vetted`
|
||||
* Used with other Rules
|
||||
* Ignore vetted user [YAML](/docs/subreddit/components/author/flairNewUserSubmission.yaml) | [JSON](/docs/subreddit/components/author/flairNewUserSubmission.json5) - Short-circuit the Check if the Author has the `vet` flair
|
||||
* Ignore vetted user [YAML](/docs/subreddit/componentscomponents/author/flairNewUserSubmission.yaml) | [JSON](/docs/subreddit/componentscomponents/author/flairNewUserSubmission.json5) - Short-circuit the Check if the Author has the `vet` flair
|
||||
|
||||
## Filter
|
||||
|
||||
@@ -35,7 +35,7 @@ All **Rules** and **Checks** have an optional `authorIs` property that takes an
|
||||
|
||||
### Examples
|
||||
|
||||
* Skip recent activity check based on author [YAML](/docs/subreddit/components/author/authorFilter.yaml) | [JSON](/docs/subreddit/components/author/authorFilter.json5) - Skip a Recent Activity check for a set of subreddits if the Author of the Submission has any set of flairs.
|
||||
* Skip recent activity check based on author [YAML](/docs/subreddit/componentscomponents/author/authorFilter.yaml) | [JSON](/docs/subreddit/componentscomponents/author/authorFilter.json5) - Skip a Recent Activity check for a set of subreddits if the Author of the Submission has any set of flairs.
|
||||
|
||||
## Flair users and submissions
|
||||
|
||||
@@ -45,4 +45,4 @@ Consult [User Flair schema](https://json-schema.app/view/%23%2Fdefinitions%2FUse
|
||||
|
||||
### Examples
|
||||
|
||||
* OnlyFans submissions [YAML](/docs/subreddit/components/author/onlyfansFlair.yaml) | [JSON](/docs/subreddit/components/author/onlyfansFlair.json5) - Check whether submitter has typical OF keywords in their profile and flair both author + submission accordingly.
|
||||
* OnlyFans submissions [YAML](/docs/subreddit/componentscomponents/author/onlyfansFlair.yaml) | [JSON](/docs/subreddit/componentscomponents/author/onlyfansFlair.json5) - Check whether submitter has typical OF keywords in their profile and flair both author + submission accordingly.
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
// for this to pass the Author of the Submission must not have the flair "Supreme Memer" and have the name "user1" or "user2"
|
||||
{
|
||||
"flairText": ["Supreme Memer"],
|
||||
"name": ["user1","user2"]
|
||||
"names": ["user1","user2"]
|
||||
},
|
||||
{
|
||||
// for this to pass the Author of the Submission must not have the flair "Decent Memer"
|
||||
|
||||
@@ -30,7 +30,7 @@ runs:
|
||||
# for this to pass the Author of the Submission must not have the flair "Supreme Memer" and have the name "user1" or "user2"
|
||||
- flairText:
|
||||
- Supreme Memer
|
||||
name:
|
||||
names:
|
||||
- user1
|
||||
- user2
|
||||
# for this to pass the Author of the Submission must not have the flair "Decent Memer"
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
# ContextMod Cookbook
|
||||
|
||||
Here you will find useful configs for CM that provide real-world functionality. This is where you should look first for **"how do i..."** questions.
|
||||
|
||||
## How To Use
|
||||
|
||||
Each recipe includes what type of config piece it is (Rule, Check, Action, Run, etc...). Keep this in mind before copy-pasting to make sure it goes in the right place in your config.
|
||||
|
||||
### Copy-Pasting
|
||||
|
||||
If the type is **Check** or **Run** the recipe contents will have instructions in the comments on how to use it as a **full subreddit config** OR **by itself (default).** If not Check/Run then when copy-pasting you will need to ensure it is placed in the correct spot in your config.
|
||||
|
||||
|
||||
### As Config Fragment
|
||||
|
||||
**Checks, Runs, Actions, and Rule** recipes can be referenced in your config without copy-pasting by using them as [Config Fragments.](/docs/subreddit/components/README.md#partial-configurations) These need to be placed in the correct spot in your config, just like copy-pasting, but only require the URL of the recipe instead of all the code.
|
||||
|
||||
To use a recipe as a fragment **copy** the URL of the config and insert into your config like this:
|
||||
|
||||
```yaml
|
||||
- 'url:https://URL_TO_CONFIG'
|
||||
```
|
||||
|
||||
EXAMPLE: Using the **Config** link from the [Free Karma](#remove-submissions-from-users-who-have-used-freekarma-subs-to-bypass-karma-checks) check below -- copy the **Config** link and insert it into a full subreddit config like this:
|
||||
|
||||
<details>
|
||||
<summary>Config</summary>
|
||||
|
||||
```yaml
|
||||
polling:
|
||||
- newSub
|
||||
runs:
|
||||
- name: MyFirstRun
|
||||
checks:
|
||||
# freekarma check
|
||||
- 'url:https://github.com/FoxxMD/context-mod/blob/master/docs/subreddit/components/cookbook/freekarma.yaml'
|
||||
- name: MyRegularCheck
|
||||
kind: submission
|
||||
# ...
|
||||
```
|
||||
</details>
|
||||
|
||||
# Recipes
|
||||
|
||||
## Spam Prevention
|
||||
|
||||
### Remove submissions from users who have used 'freekarma' subs to bypass karma checks
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/freekarma.yaml)
|
||||
|
||||
If the user has any activity (comment/submission) in known freekarma subreddits in the past (100 activities) then remove the submission.
|
||||
|
||||
### Remove submissions that are consecutively spammed by the author
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/crosspostSpam.yaml)
|
||||
|
||||
If the user has crossposted the same submission in the past (100 activities) 4 or more times in a row then remove the submission.
|
||||
|
||||
### Remove submissions if users is flooding new
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/floodingNewSubmissions.yaml)
|
||||
|
||||
If the user has made more than 4 submissions in your subreddit in the last 24 hours than new submissions are removed and user is tagged with a modnote.
|
||||
|
||||
### Remove submissions posted in diametrically-opposed subreddit
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/diametricSpam.yaml)
|
||||
|
||||
If the user makes the same submission to another subreddit(s) that are "thematically" opposed to your subreddit it is probably spam. This check removes it. Detects all types of submissions (including images).
|
||||
|
||||
### Remove comments that are consecutively spammed by the author
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/commentSpam.yaml)
|
||||
|
||||
If the user made the same comment (with some fuzzy matching) 4 or more times in a row in the past (100 activities or 6 months) then remove the comment.
|
||||
|
||||
### Remove comment if it is a chat invite link spam
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/chatSpam.yaml)
|
||||
|
||||
This rule goes a step further than automod can by being more discretionary about how it handles this type of spam.
|
||||
|
||||
* Remove the comment if:
|
||||
* Comment being checked contains **only** a chat link (no other text) OR
|
||||
* Chat links appear **anywhere** in three or more of the last 100 comments the Author has made
|
||||
|
||||
This way ContextMod can more easily distinguish between these use cases for a user commenting with a chat link:
|
||||
|
||||
* actual spammers who only spam a chat link
|
||||
* users who may comment with a link but have context for it either in the current comment or in their history
|
||||
* users who many comment with a link but it's a one-off event (no other links historically)
|
||||
|
||||
## Repost Detection
|
||||
|
||||
### Remove comments reposted from youtube video submissions
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/youtubeCommentRepost.yaml)
|
||||
|
||||
**Requires bot has an API Key for Youtube.**
|
||||
|
||||
Removes comment on reddit if the same comment is found on the youtube video the submission is for.
|
||||
|
||||
### Remove comments reposted from reddit submissions
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/commentRepost.yaml)
|
||||
|
||||
Checks top-level comments on submissions younger than 30 minutes:
|
||||
* Finds other reddit submissions based on crosspost/duplicates/title/URL, takes top 10 submissions based # of upvotes
|
||||
* If this comment matches any top comments from those other submissions with at least 85% sameness then it is considered a repost and removed
|
||||
|
||||
### Remove reposted reddit submission
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/submissionRepost.yaml)
|
||||
|
||||
Checks reddit for top posts with a **Title** that is 90% or more similar to the submission being checked and removes it, if found.
|
||||
|
||||
## Self Promotion
|
||||
|
||||
### Remove link submissions where the user's history is comprised of 10% or more of the same link
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/selfPromo.yaml)
|
||||
|
||||
If the link origin (youtube author, twitter author, etc. or regular domain for non-media links)
|
||||
|
||||
* comprises 10% or more of the users **entire** history in the past (100 activities or 6 months)
|
||||
* or comprises 10% or more of the users **submission** history in the past (100 activities or 6 months) and the user has low engagement (<50% of history is comments or 40%> of comment are as OP)
|
||||
|
||||
then remove the submission
|
||||
|
||||
### Remove submissions posted in 'newtube' subreddits
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/newtube.yaml)
|
||||
|
||||
If the user makes the same submission to a 'newtube' or self-promotional subreddit it is removed and a modnote is added.
|
||||
|
||||
## Safety
|
||||
|
||||
### Remove comments on brigaded submissions when user has no history
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/brigadingNoHistory.yaml)
|
||||
|
||||
The users of comments on a brigaded submission (based on a special submission flair) have their comment history checked -- if they have no participation in your subreddit then the comment is removed.
|
||||
|
||||
### Remove submissions from users with a history of sex solicitation
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/sexSolicitationHistory.yaml)
|
||||
|
||||
If the author of a submission has submissions in their history that match common reddit "sex solicitation" tags (MFA, R4F, M4F, etc...) the submission is removed and a modnote added.
|
||||
|
||||
This is particularly useful for subreddits with underage audiences or mentally/emotionally vulnerable groups.
|
||||
|
||||
The check can be modified to removed comments by changing `kind: submission` to `kind: comment`
|
||||
|
||||
## Verification
|
||||
|
||||
### Verify users from r/TranscribersOfReddit
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/transcribersOfReddit.yaml)
|
||||
|
||||
[r/TranscribersOfReddit](https://www.reddit.com/r/transcribersofreddit) is a community of volunteers transcribing images and videos, across reddit, into plain text.
|
||||
|
||||
This Check detects their standard transcription template and also checks they have a history in r/transcribersofreddit -- then approves the comment and flairs the user with **Transcriber ✍️**
|
||||
|
||||
### Require submission authors have prior subreddit participation
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/requireNonOPParticipation.yaml)
|
||||
|
||||
Submission is removed if the author has **less than 5 non-OP comments** in your subreddit prior to making the submission.
|
||||
|
||||
### Require submission authors make a top-level comment with 15 minutes of posting
|
||||
|
||||
* Type: **Check**
|
||||
* [Config](/docs/subreddit/components/cookbook/requireNonOPParticipation.yaml)
|
||||
|
||||
After making a submission the author must make a top-level comment with a regex-checkable pattern within X minutes. If the comment is not made the submission is removed.
|
||||
|
||||
# Monitoring
|
||||
|
||||
### Sticky a comment on popular submissions
|
||||
|
||||
* Type: **Run**
|
||||
* [Config](/docs/subreddit/components/cookbook/popularSubmissionMonitoring.yaml)
|
||||
|
||||
This **Run** should come after any other Runs you have that may remove a Submission.
|
||||
|
||||
The Run will cause CM to check new submissions for 3 hours at a 10 minute interval. The bot will then make a comment and sticky it WHEN it detects the number of upvotes is abnormal for how long the Submission has been "alive".
|
||||
@@ -1,44 +0,0 @@
|
||||
#polling:
|
||||
# - newComm
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Report comments from users with no history in the subreddit IF the submission is flaired as being brigaded
|
||||
# optionally, remove comment
|
||||
#
|
||||
- name: Brigading No History
|
||||
kind: comment
|
||||
# only runs on comments in a submission with a link flair css class of 'brigaded'
|
||||
itemIs:
|
||||
- submissionState:
|
||||
# can use any or all of these to detect brigaded submission
|
||||
- link_flair_css: brigaded
|
||||
#flairTemplate: 123-1234
|
||||
#link_flair_text: Restricted
|
||||
rules:
|
||||
- name: noHistory
|
||||
kind: recentActivity
|
||||
# check last 100 activities that have not been removed
|
||||
window:
|
||||
count: 100
|
||||
filterOn:
|
||||
post:
|
||||
commentState:
|
||||
include:
|
||||
- removed: false
|
||||
thresholds:
|
||||
# triggers if user has only one activity (this one) in your subreddit
|
||||
- subreddits:
|
||||
- MYSUBREDDIT
|
||||
threshold: '<= 1'
|
||||
actions:
|
||||
- kind: report
|
||||
enable: true
|
||||
content: User has no history in subreddit
|
||||
|
||||
- kind: remove
|
||||
enable: false
|
||||
note: User has no history in subreddit
|
||||
@@ -1,71 +0,0 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
# - newComm
|
||||
#runs:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a series of RUNS
|
||||
- name: approvals
|
||||
checks:
|
||||
- name: approveSubmissionOnComment
|
||||
description: Approve an unapproved submission when OP comments with the magic words
|
||||
kind: comment
|
||||
itemIs:
|
||||
# only check comment if submission is not approved and this comment is by OP
|
||||
- submissionState:
|
||||
- approved: false
|
||||
op: true
|
||||
rules:
|
||||
- name: OPMagic
|
||||
kind: regex
|
||||
criteria:
|
||||
# YOU NEED TO EDIT THIS REGEX TO MATCH THE PATTERN THE OP'S COMMENT SHOULD HAVE IN ORDER TO VERIFY THE SUBMISSION
|
||||
- regex: '/Say Please/i'
|
||||
actions:
|
||||
- kind: approve
|
||||
targets:
|
||||
- parent
|
||||
- self
|
||||
# cancel any delayed dispatched actions
|
||||
- kind: cancelDispatch
|
||||
# tell action to look for delayed items matched parent (submission)
|
||||
target: parent
|
||||
# submission must have 'subVerification' identifier
|
||||
identifier: subVerification
|
||||
|
||||
- name: verification
|
||||
checks:
|
||||
- name: waitForVerification
|
||||
description: Delay processing this submission for 15 minutes
|
||||
kind: submission
|
||||
itemIs:
|
||||
# only dispatch if this is the first time we are seeing this submission
|
||||
- source:
|
||||
- "poll:newSub"
|
||||
- user
|
||||
actions:
|
||||
- kind: dispatch
|
||||
target: self
|
||||
# unique identifier which is a nice hint in the UI and also allows targeting this item while it is delayed
|
||||
identifier: subVerification
|
||||
delay: "15 minutes"
|
||||
# when it is reprocessed go directly to the 'verification' run, skipping everything else
|
||||
goto: verification
|
||||
|
||||
- name: removeNoVerification
|
||||
description: Remove submission if it is not verified after delay
|
||||
kind: submission
|
||||
itemIs:
|
||||
# only process this submission if it comes dispatch with 'subVerification' identifier and is NOT approved after 15 minutes
|
||||
- source: "dispatch:subVerification"
|
||||
approved: false
|
||||
actions:
|
||||
# if this submission is being processed it has been 5 minutes and was not cancelled by OF comment
|
||||
- kind: remove
|
||||
enable: true
|
||||
|
||||
- kind: comment
|
||||
enable: true
|
||||
lock: true
|
||||
distinguish: true
|
||||
content: 'Your submission has been removed because you did not follow verification instructions within 15 minutes of posting.'
|
||||
@@ -1,54 +0,0 @@
|
||||
#polling:
|
||||
# - newComm
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Checks top-level comments on submissions younger than 30 minutes:
|
||||
# * Finds other reddit submissions based on crosspost/duplicates/title/URL, takes top 10 submissions based # of upvotes
|
||||
# * If this comment matches any comments from those other submissions with at least 85% sameness then it is considered repost
|
||||
#
|
||||
# optionally, bans user if they have more than one modnote for comment reposts
|
||||
#
|
||||
- name: commRepost
|
||||
description: Check if comment has been reposted from youtube
|
||||
kind: comment
|
||||
itemIs:
|
||||
- removed: false
|
||||
approved: false
|
||||
op: false
|
||||
# top level comments only
|
||||
depth: '< 1'
|
||||
submissionState:
|
||||
- age: '< 30 minutes'
|
||||
condition: AND
|
||||
rules:
|
||||
- name: commRepost
|
||||
kind: repost
|
||||
criteria:
|
||||
- searchOn:
|
||||
- external
|
||||
actions:
|
||||
- kind: remove
|
||||
spam: true
|
||||
note: 'reposted comment from reddit with {{rules.commrepost.closestSameness}}% sameness'
|
||||
|
||||
- kind: ban
|
||||
authorIs:
|
||||
# if the author has more than one spamwatch usernote then just ban em
|
||||
include:
|
||||
- modActions:
|
||||
- noteType: SPAM_WATCH
|
||||
note: "/comment repost.*/i"
|
||||
search: total
|
||||
count: "> 1"
|
||||
message: You have been banned for repeated spammy behavior including reposting reddit comments
|
||||
note: reddit comment repost + spammy behavior
|
||||
reason: reddit comment repost + spammy behavior
|
||||
|
||||
- name: commRepostModNote
|
||||
kind: modnote
|
||||
content: 'YT comment repost with {{rules.commrepost.closestSameness}}% sameness'
|
||||
type: SPAM_WATCH
|
||||
@@ -1,34 +0,0 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
- name: diametricSpam
|
||||
description: Check if author has posted the same image in opposite subs
|
||||
kind: submission
|
||||
rules:
|
||||
- name: recent
|
||||
kind: recentActivity
|
||||
useSubmissionAsReference: true
|
||||
# requires your subreddit to be running on a CM instance that supports image processing
|
||||
imageDetection:
|
||||
enable: true
|
||||
threshold: 5
|
||||
lookAt: submissions
|
||||
window: 30
|
||||
thresholds:
|
||||
- threshold: ">= 1"
|
||||
subreddits:
|
||||
- AnotherSubreddit
|
||||
actions:
|
||||
- kind: remove
|
||||
enable: true
|
||||
content: "Posted same image in {{rules.recent.subSummary}}"
|
||||
|
||||
- kind: comment
|
||||
distinguish: true
|
||||
sticky: true
|
||||
lock: true
|
||||
content: 'You have posted the same image in another subreddit ({{rules.recent.subSummary}}) that does not make sense given the theme of this subreddit. We consider this spam and it has been removed.'
|
||||
@@ -1,34 +0,0 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Add a mote note to users who are making more than 4 submissions a day
|
||||
# and optionally remove new submissions by them
|
||||
#
|
||||
- name: Flooding New
|
||||
description: Detect users make more than 4 submission in 24 hours
|
||||
kind: submission
|
||||
rules:
|
||||
- name: Recent In Sub
|
||||
kind: recentActivity
|
||||
useSubmissionAsReference: false
|
||||
window:
|
||||
duration: 24 hours
|
||||
fetch: submissions
|
||||
thresholds:
|
||||
- subreddits:
|
||||
# change this to your subreddit
|
||||
- MYSUBREDDIT
|
||||
threshold: "> 4"
|
||||
actions:
|
||||
- kind: modnote
|
||||
type: SPAM_WATCH
|
||||
content: '{{rules.recentinsub.totalCount}} submissions in the last 24 hours'
|
||||
|
||||
- kind: remove
|
||||
enable: false
|
||||
note: '{{rules.recentinsub.totalCount}} submissions in the last 24 hours'
|
||||
@@ -1,45 +0,0 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Remove submissions from users who have recent activity in freekarma subs in the last 100 activities
|
||||
#
|
||||
- name: freekarma removal
|
||||
description: Remove submission if user has used freekarma sub recently
|
||||
kind: submission
|
||||
rules:
|
||||
- name: freekarma
|
||||
kind: recentActivity
|
||||
window: 100
|
||||
useSubmissionAsReference: false
|
||||
thresholds:
|
||||
- subreddits:
|
||||
- FreeKarma4U
|
||||
- FreeKarma4You
|
||||
- freekarmaforyou
|
||||
- KarmaFarming4Pros
|
||||
- KarmaStore
|
||||
- upvote
|
||||
- promote
|
||||
- shamelessplug
|
||||
- upvote
|
||||
- FreeUpVotes
|
||||
- GiveMeKarma
|
||||
- nsfwkarma
|
||||
- GetFreeKarmaAnyTime
|
||||
- freekarma2021
|
||||
- FreeKarma2022
|
||||
- KarmaRocket
|
||||
- FREEKARMA4PORN
|
||||
actions:
|
||||
- kind: report
|
||||
enable: false
|
||||
content: 'Remove => {{rules.freekarma.totalCount}} activities in freekarma subs'
|
||||
|
||||
- kind: remove
|
||||
enable: true
|
||||
note: '{{rules.freekarma.totalCount}} activities in freekarma subs'
|
||||
@@ -1,55 +0,0 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Add a mote note to users who make a submission that is also posted to a 'newtube' subreddit
|
||||
# and optionally remove new submission
|
||||
#
|
||||
- name: Newtube Submission
|
||||
description: Tag user if submission was posted in 'newtube' subreddit
|
||||
kind: submission
|
||||
rules:
|
||||
- name: newTube
|
||||
kind: recentActivity
|
||||
window:
|
||||
count: 100
|
||||
fetch: submissions
|
||||
thresholds:
|
||||
- subreddits:
|
||||
- AdvertiseYourVideos
|
||||
- BrandNewTube
|
||||
- FreeKarma4U
|
||||
- FreeKarma4You
|
||||
- KarmaStore
|
||||
- GetMoreSubsYT
|
||||
- GetMoreViewsYT
|
||||
- NewTubers
|
||||
- promote
|
||||
- PromoteGamingVideos
|
||||
- shamelessplug
|
||||
- SelfPromotionYouTube
|
||||
- SmallYTChannel
|
||||
- SmallYoutubers
|
||||
- upvote
|
||||
- youtubestartups
|
||||
- YouTube_startups
|
||||
- YoutubeSelfPromotions
|
||||
- YoutubeSelfPromotion
|
||||
- YouTubeSubscribeBoost
|
||||
- youtubepromotion
|
||||
- YTPromo
|
||||
- Youtubeviews
|
||||
- YouTube_startups
|
||||
actions:
|
||||
- name: newtubeModTag
|
||||
kind: modnote
|
||||
type: SPAM_WATCH
|
||||
content: 'New Tube => {{rules.newtube.subSummary}}{{rules.newtubeall.subSummary}}'
|
||||
|
||||
- kind: remove
|
||||
enable: false
|
||||
note: 'New Tube => {{rules.newtube.subSummary}}{{rules.newtubeall.subSummary}}'
|
||||
@@ -1,89 +0,0 @@
|
||||
polling:
|
||||
- newSub
|
||||
|
||||
runs:
|
||||
- name: MyRegularRun
|
||||
itemIs:
|
||||
# regular run/checks should only run on new activities or if from dashboard
|
||||
- source:
|
||||
- 'poll:newSub'
|
||||
- 'poll:newComm'
|
||||
- 'user'
|
||||
checks:
|
||||
- name: RuleBreakingCheck1
|
||||
kind: submission
|
||||
# ...
|
||||
#
|
||||
# your regular checks go here
|
||||
#
|
||||
# assuming if a Submission makes it through all of your Checks then it is "OK"
|
||||
# to be Approved or generally will be visible in the subreddit (valid for monitoring for r/All)
|
||||
# -- at the end of the Run add a Dispath action
|
||||
- name: Dispatch For Popular Monitoring
|
||||
kind: submission
|
||||
actions:
|
||||
- kind: dispatch
|
||||
identifier: 'popular'
|
||||
# CM will wait 5 minutes before processing this submission again
|
||||
delay: '5 minutes'
|
||||
target: 'self'
|
||||
|
||||
# a separate run that only processes Submissions from dispatch:popular
|
||||
- name: PopularWatch
|
||||
itemIs:
|
||||
- source: 'dispatch:popular'
|
||||
checks:
|
||||
# each check here looks at submission age and tests upvotes against what you think is probably r/All number of votes
|
||||
# in descending age (oldest first)
|
||||
# NOTE: You should change the 'age' and 'score' tests to fit the traffic volume for your subreddit!
|
||||
- name: Two Hour Check
|
||||
kind: submission
|
||||
itemIs:
|
||||
- age: '>= 2 hours'
|
||||
score: '> 100'
|
||||
actions:
|
||||
- kind: comment
|
||||
name: popularComment
|
||||
content: 'Looks like this thread is getting a lot of attention. Greetings r/All! Please keep it civil.'
|
||||
sticky: true
|
||||
distinguish: true
|
||||
lock: true
|
||||
|
||||
- name: One Hour Check
|
||||
kind: submission
|
||||
itemIs:
|
||||
- age: '>= 1 hours'
|
||||
score: '> 50'
|
||||
actions:
|
||||
- popularComment
|
||||
|
||||
- name: Thirty Minute Check
|
||||
kind: submission
|
||||
itemIs:
|
||||
- age: '>= 30 minutes'
|
||||
score: '> 25'
|
||||
actions:
|
||||
- popularComment
|
||||
|
||||
- name: Ten Minute Check
|
||||
kind: submission
|
||||
itemIs:
|
||||
- age: '>= 10 minutes'
|
||||
score: '> 10'
|
||||
actions:
|
||||
- popularComment
|
||||
|
||||
# finally, if none of the popular checks passed re-dispatch submission to be checked in another 10 minutes
|
||||
- name: Delay Popular Check
|
||||
kind: submission
|
||||
postTrigger:
|
||||
# don't need to add this Actioned Events
|
||||
recordTo: false
|
||||
itemIs:
|
||||
# only monitor until submission is 3 hours old
|
||||
- age: '<= 3 hours'
|
||||
actions:
|
||||
- kind: dispatch
|
||||
identifier: 'popular'
|
||||
delay: '10 minutes'
|
||||
target: 'self'
|
||||
@@ -1,51 +0,0 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Report submissions by users with less than 5 non-OP comments in our subreddit
|
||||
# and optionally remove the submission
|
||||
#
|
||||
- name: RequireEngagement
|
||||
description: Remove submission if author has less than X non-op comments in our subreddit
|
||||
kind: submission
|
||||
rules:
|
||||
- name: LittleEngagement
|
||||
kind: recentActivity
|
||||
lookAt: comments
|
||||
useSubmissionAsReference: false
|
||||
# bot will check the last 100 NON-OP comments from user's history
|
||||
window:
|
||||
count: 100
|
||||
fetch: comments
|
||||
filterOn:
|
||||
post:
|
||||
commentState:
|
||||
- op: false
|
||||
thresholds:
|
||||
subreddits:
|
||||
- MYSUBREDDIT
|
||||
# rule is "triggered" if there are LESS THAN 5 comments in our subreddit in the window specified (currently 100 non-op comments)
|
||||
threshold: '< 5'
|
||||
|
||||
actions:
|
||||
|
||||
- kind: report # report the submission
|
||||
enable: true
|
||||
# the text of the report
|
||||
content: 'User has <5 non-OP comments in last 100 comments'
|
||||
|
||||
- kind: remove # remove the submission
|
||||
enable: false
|
||||
note: 'User has <5 non-OP comments in last 100 comments'
|
||||
|
||||
- kind: comment # reply to submission with a comment
|
||||
enable: false
|
||||
# contents of the comment
|
||||
content: We require users to have a minimum level of engagement (>5 comments on other people's posts) in our subreddit before making submissions. Your submission has been automatically removed.
|
||||
sticky: true
|
||||
distinguish: true
|
||||
lock: true
|
||||
@@ -1,33 +0,0 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Remove submission if user has any "redditor for [sex]..." submissions in their history
|
||||
# and optionally bans user
|
||||
#
|
||||
- name: sexSpamHistory
|
||||
description: Detect sex spam language in recent history and ban if found (most likely a bot)
|
||||
kind: submission
|
||||
rules:
|
||||
- kind: regex
|
||||
name: redditorFor
|
||||
criteria:
|
||||
# matches if text has common "looking for" acronym like F4M R4A etc...
|
||||
- regex: '/[RFM]4[a-zA-Z\s0-9]/i'
|
||||
totalMatchThreshold: "> 1"
|
||||
window: 100
|
||||
testOn:
|
||||
- body
|
||||
- title
|
||||
actions:
|
||||
- kind: remove
|
||||
enable: true
|
||||
note: 'Has sex solicitation submission history: {{rules.redditorfor.matchSample}}'
|
||||
|
||||
- kind: modnote
|
||||
type: ABUSE_WARNING
|
||||
content: 'Has sex solicitation submission history: {{rules.redditorfor.matchSample}}'
|
||||
@@ -1,31 +0,0 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
- name: BotRepost
|
||||
description: Remove submission if it is likely a repost
|
||||
kind: submission
|
||||
rules:
|
||||
# search reddit for similar submissions to see if it is a repost
|
||||
- name: subRepost
|
||||
kind: repost
|
||||
criteria:
|
||||
- searchOn:
|
||||
# match found Submissions sameness using title against title of Submission being checked
|
||||
- kind: title
|
||||
# sameness (confidence) % of a title required to consider Submission being checked as a repost
|
||||
matchScore: 90
|
||||
|
||||
actions:
|
||||
# report the submission
|
||||
- kind: report
|
||||
enable: true
|
||||
content: '{{rules.subrepost.closestSameness}} confidence this is a repost.'
|
||||
|
||||
# remove the submission
|
||||
- kind: remove
|
||||
enable: false
|
||||
note: '{{rules.subrepost.closestSameness}} confidence this is a repost.'
|
||||
@@ -1,41 +0,0 @@
|
||||
#polling:
|
||||
# - newComm
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Detect top-level comments by users from r/transcribersofreddit
|
||||
# and approve/flair the user
|
||||
#
|
||||
- name: transcriber comment
|
||||
description: approve/flair transcribed video comment
|
||||
kind: comment
|
||||
itemIs:
|
||||
# top-level comments
|
||||
depth: '< 1'
|
||||
condition: AND
|
||||
rules:
|
||||
- name: transcribedVideoFormat
|
||||
kind: regex
|
||||
criteria:
|
||||
- regex: '/^[\n\r\s]*\*Video Transcription\*[\n\r]+---[\S\s]+---/gim'
|
||||
- name: transcribersActivity
|
||||
kind: recentActivity
|
||||
window:
|
||||
count: 100
|
||||
duration: 1 week
|
||||
useSubmissionAsReference: false
|
||||
thresholds:
|
||||
- subreddits:
|
||||
- transcribersofreddit
|
||||
actions:
|
||||
- kind: approve
|
||||
- name: flairTranscriber
|
||||
kind: flair
|
||||
authorIs:
|
||||
exclude:
|
||||
- flairText:
|
||||
- Transcriber ✍️
|
||||
text: Transcriber ✍️
|
||||
@@ -1,47 +0,0 @@
|
||||
#polling:
|
||||
# - newComm
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# If submission type is a youtube video CM will check top comments on the video and remove comment if it at least 85% the same
|
||||
# optionally, bans user if they have more than one modnote for comment reposts
|
||||
#
|
||||
- name: commRepostYT
|
||||
description: Check if comment has been reposted from youtube
|
||||
kind: comment
|
||||
itemIs:
|
||||
- removed: false
|
||||
approved: false
|
||||
op: false
|
||||
condition: AND
|
||||
rules:
|
||||
- name: commRepost
|
||||
kind: repost
|
||||
criteria:
|
||||
- searchOn:
|
||||
- external
|
||||
actions:
|
||||
- kind: remove
|
||||
spam: true
|
||||
note: 'reposted comment from youtube with {{rules.commrepostyt.closestSameness}}% sameness'
|
||||
|
||||
- kind: ban
|
||||
authorIs:
|
||||
# if the author has more than one spamwatch usernote then just ban em
|
||||
include:
|
||||
- modActions:
|
||||
- noteType: SPAM_WATCH
|
||||
note: "/comment repost.*/i"
|
||||
search: total
|
||||
count: "> 1"
|
||||
message: You have been banned for repeated spammy behavior including reposting youtube comments
|
||||
note: yt comment repost + spammy behavior
|
||||
reason: yt comment repost + spammy behavior
|
||||
|
||||
- name: commRepostYTModNote
|
||||
kind: modnote
|
||||
content: 'YT comment repost with {{rules.commrepostyt.closestSameness}}% sameness'
|
||||
type: SPAM_WATCH
|
||||
@@ -5,64 +5,10 @@ The **History** rule can check an Author's submission/comment statistics over a
|
||||
* Submission total or percentage of All Activity
|
||||
* Comment total or percentage of all Activity
|
||||
* Comments made as OP (commented in their own Submission) total or percentage of all Comments
|
||||
* Ratio of activities against another window of activities
|
||||
|
||||
Consult the [schema](https://json-schema.app/view/%23%2Fdefinitions%2FHistoryJSONConfig?url=https%3A%2F%2Fraw.githubusercontent.com%2FFoxxMD%2Fcontext-mod%2Fmaster%2Fsrc%2FSchema%2FApp.json) for a complete reference of the rule's properties.
|
||||
|
||||
## Ratio
|
||||
|
||||
Use the `ratio` property in Criteria to test the [number of activities](/docs/subreddit/activitiesWindow.md) found in the parent criteria against the number of activities from _another_ [activity window](/docs/subreddit/activitiesWindow.md) defined in the ratio.
|
||||
|
||||
Example:
|
||||
|
||||
```yaml
|
||||
- kind: history
|
||||
criteria:
|
||||
# "parent" criteria, returns all activities, in the last 100 from user's history, that occurred in r/mealtimevideos
|
||||
- window:
|
||||
count: 100
|
||||
filterOn:
|
||||
post:
|
||||
subreddits:
|
||||
include:
|
||||
- mealtimevideos
|
||||
ratio:
|
||||
# "ratio" criteria, returns all activities, in the last 100 from user's history, that occurred in r/redditdev
|
||||
window:
|
||||
count: 100
|
||||
filterOn:
|
||||
post:
|
||||
subreddits:
|
||||
include:
|
||||
- redditdev
|
||||
# test (number of parent criteria activities) / (number of ratio critieria activities)
|
||||
threshold: '> 1.2'
|
||||
```
|
||||
|
||||
`threshold` may be a number or percentage `(number * 100)`
|
||||
|
||||
* EX `> 1.2` => There are 1.2 activities from parent criteria for every 1 ratio activities
|
||||
* EX `<= 75%` => There are equal to or less than 0.75 activities from parent criteria for every 1 ratio activities
|
||||
|
||||
### Examples
|
||||
|
||||
* Low Comment Engagement [YAML](/docs/subreddit/components/history/lowEngagement.yaml) | [JSON](/docs/subreddit/components/history/lowEngagement.json5) - Check if Author is submitting much more than they comment.
|
||||
* OP Comment Engagement [YAML](/docs/subreddit/components/history/opOnlyEngagement.yaml) | [JSON](/docs/subreddit/components/history/opOnlyEngagement.json5) - Check if Author is mostly engaging only in their own content
|
||||
|
||||
# [Template Variables](/docs/subreddit/actionTemplating.md)
|
||||
|
||||
| Name | Description | Example |
|
||||
|----------------------|------------------------------------------------------------------------|----------------------------------------------------|
|
||||
| `result` | Summary of rule results (also found in Actioned Events) | Filtered Activities (7) were < 10 Items (2 months) |
|
||||
| `activityTotal` | Total number of activities from window | 50 |
|
||||
| `filteredTotal` | Total number of activities filtered from window | 7 |
|
||||
| `filteredPercent` | Percentage of activities filtered from window | 14% |
|
||||
| `submissionTotal` | Total number of filtered submissions from window | 4 |
|
||||
| `submissionPercent` | Percentage of filtered submissions from window | 8% |
|
||||
| `commentTotal` | Total number of filtered comments from window | 3 |
|
||||
| `commentPercent` | Percentage of filtered comments from window | 6% |
|
||||
| `opTotal` | Total number of comments as OP from filtered comments | 2 |
|
||||
| `opPercent` | Percentage of comments as OP from filtered comments | 66% |
|
||||
| `thresholdSummary` | A text summary of the first Criteria triggered with totals/percentages | Filtered Activities (7) were < 10 Items |
|
||||
| `subredditBreakdown` | A markdown list of filtered activities by subreddit | * SubredditA - 5 (71%) \n * Subreddit B - 2 (28%) |
|
||||
| `window` | Number or duration of Activities considered from window | 2 months |
|
||||
* Low Comment Engagement [YAML](/docs/subreddit/componentscomponents/history/lowEngagement.yaml) | [JSON](/docs/subreddit/componentscomponents/history/lowEngagement.json5) - Check if Author is submitting much more than they comment.
|
||||
* OP Comment Engagement [YAML](/docs/subreddit/componentscomponents/history/opOnlyEngagement.yaml) | [JSON](/docs/subreddit/componentscomponents/history/opOnlyEngagement.json5) - Check if Author is mostly engaging only in their own content
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
# Table of Contents
|
||||
|
||||
* [Overview](#overview)
|
||||
* [MHS Predictions](#mhs-predictions)
|
||||
* [Flagged](#flagged)
|
||||
* [Confidence](#confidence)
|
||||
* [Usage](#usage)
|
||||
* [Minimal/Default Config](#minimaldefault-config)
|
||||
* [Full Config](#full-config)
|
||||
* [Historical Matching](#historical-matching)
|
||||
* [Examples](#examples)
|
||||
|
||||
# Overview
|
||||
|
||||
[moderatehatespeech.com](https://moderatehatespeech.com/) (MHS) is a [non-profit initiative](https://moderatehatespeech.com/about/) to identify and fight toxic and hateful content online using programmatic technology such as machine learning models.
|
||||
|
||||
They offer a [toxic content prediction model](https://moderatehatespeech.com/framework/) specifically trained on and for [reddit content](https://www.reddit.com/r/redditdev/comments/xdscbo/updated_bot_backed_by_moderationoriented_ml_for/) as well as partnering [directly with subreddits.](https://moderatehatespeech.com/research/subreddit-program/).
|
||||
|
||||
Context Mod leverages their [API](https://moderatehatespeech.com/docs/) for toxic content predictions in the **MHS Rule.**
|
||||
|
||||
The **MHS Rule** sends an Activity's content (title or body) to MHS which returns a prediction on whether the content is toxic and actionable by a moderator.
|
||||
|
||||
## MHS Predictions
|
||||
|
||||
MHS's toxic content predictions return two indicators about the content it analyzed. Both are available as test conditions in ContextMod.
|
||||
|
||||
### Flagged
|
||||
|
||||
MHS returns a straight "Toxic or Normal" **flag** based on how it classifies the content.
|
||||
|
||||
Example
|
||||
|
||||
* `Normal` - "I love those pineapples"
|
||||
* `Toxic` - "why are we having all these people from shithole countries coming here"
|
||||
|
||||
### Confidence
|
||||
|
||||
MHS returns how **confident** it is of the flag classification on a scale of 0 to 100.
|
||||
|
||||
Example
|
||||
|
||||
"why are we having all these people from shithole countries coming here"
|
||||
|
||||
* Flag = `Toxic`
|
||||
* Confidence = `97.12` -> The model is 97% confident the content is `Toxic`
|
||||
|
||||
# Usage
|
||||
|
||||
**An MHS Api Key is required to use this Rule**. An API Key can be acquired, for free, by creating an account at [moderatehatespeech.com](https://moderatehatespeech.com).
|
||||
|
||||
The Key can be provided by the bot's Operator in the [bot config credentials](https://json-schema.app/view/%23/%23%2Fdefinitions%2FBotInstanceJsonConfig/%23%2Fdefinitions%2FBotCredentialsJsonConfig?url=https%3A%2F%2Fraw.githubusercontent.com%2FFoxxMD%2Fcontext-mod%2Fedge%2Fsrc%2FSchema%2FOperatorConfig.json) or in the subreddit's config in the top-level `credentials` property like this:
|
||||
|
||||
```yaml
|
||||
credentials:
|
||||
mhs:
|
||||
apiKey: 'myMHSApiKey'
|
||||
|
||||
# the rest of your config below
|
||||
polling:
|
||||
# ...
|
||||
runs:
|
||||
# ...
|
||||
```
|
||||
|
||||
### Minimal/Default Config
|
||||
|
||||
ContextMod provides a reasonable default configuration for the MHS Rule if you do not wish to configure it yourself. The default configuration will trigger the rule if the MHS prediction:
|
||||
|
||||
* flags as `toxic`
|
||||
* with `90% or greater` confidence
|
||||
|
||||
Example
|
||||
|
||||
```yaml
|
||||
rules:
|
||||
- kind: mhs
|
||||
|
||||
# rest of your rules here...
|
||||
```
|
||||
|
||||
### Full Config
|
||||
|
||||
|
||||
| Property | Type | Description | Default |
|
||||
|--------------|---------|-------------------------------------------------------------------------------------------|---------|
|
||||
| `flagged` | boolean | Test whether content is flagged as toxic (true) or normal (false) | `true` |
|
||||
| `confidence` | string | Comparison against a number 0 to 100 representing how confident MHS is in the prediction | `>= 90` |
|
||||
| `testOn` | array | Which parts of the Activity to send to MHS. Options: `title` and/or `body` | `body` |
|
||||
|
||||
Example
|
||||
|
||||
```yaml
|
||||
rules:
|
||||
- kind: mhs
|
||||
criteria:
|
||||
flagged: true # triggers if MHs flags the content as toxic AND
|
||||
confidence: '> 66' # MHS is 66% or more confident in its prediction
|
||||
testOn: # send the body of the activity to the MHS prediction service
|
||||
- body
|
||||
```
|
||||
|
||||
#### Historical Matching
|
||||
|
||||
Like the [Sentiment](/docs/subreddit/components/sentiment#historical) and [Regex](/docs/subreddit/components/regex#historical) rules CM can also use MHS predictions to check content from the Author's history.
|
||||
|
||||
Example
|
||||
|
||||
```yaml
|
||||
rules:
|
||||
- kind: mhs
|
||||
# ...same config as above but can include below...
|
||||
historical:
|
||||
mustMatchCurrent: true # if true then CM will not check author's history unless current Activity matches MHS prediction criteria
|
||||
totalMatching: '> 1' # comparison for how many activities in history must match to trigger the rule
|
||||
window: 10 # specify the range of activities to check in author's history
|
||||
criteria: #... if specified, overrides parent-level criteria
|
||||
```
|
||||
|
||||
# [Template Variables](/docs/subreddit/actionTemplating.md)
|
||||
|
||||
|
||||
| Name | Description | Example |
|
||||
|-----------------|-------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `result` | Summary of rule results (also found in Actioned Events) | Current Activity MHS Test: ✓ Confidence test (>= 90) PASSED MHS confidence of 99.85% Flagged pass condition of true (toxic) MATCHED MHS flag 'toxic' |
|
||||
| `window` | Number or duration of Activities considered from window | 1 activities |
|
||||
| `criteriaTest` | MHS value to test against | MHS confidence is > 95% |
|
||||
| `totalMatching` | Total number of activities (current + historical) that matched `criteriaTest` | 1 |
|
||||
|
||||
# Examples
|
||||
|
||||
Report if MHS flags as toxic
|
||||
|
||||
```yaml
|
||||
rules:
|
||||
- kind: mhs
|
||||
actions:
|
||||
- kind: report
|
||||
content: 'MHS flagged => {{rules.mhs.summary}}'
|
||||
```
|
||||
|
||||
Report if MHS flags as toxic with 95% confidence
|
||||
|
||||
```yaml
|
||||
rules:
|
||||
- kind: mhs
|
||||
criteria:
|
||||
confidence: '>= 95'
|
||||
actions:
|
||||
- kind: report
|
||||
content: 'MHS flagged => {{rules.mhs.summary}}'
|
||||
```
|
||||
|
||||
Report if MHS flags as toxic and at least 3 recent activities in last 10 from author's history are also toxic
|
||||
|
||||
```yaml
|
||||
rules:
|
||||
- kind: mhs
|
||||
historical:
|
||||
window: 10
|
||||
mustMatchCurrent: true
|
||||
totalMatching: '>= 3'
|
||||
actions:
|
||||
- kind: report
|
||||
content: 'MHS flagged => {{rules.mhs.summary}}'
|
||||
```
|
||||
|
||||
Approve if MHS flags as NOT toxic with 95% confidence
|
||||
|
||||
```yaml
|
||||
rules:
|
||||
- kind: mhs
|
||||
criteria:
|
||||
confidence: '>= 95'
|
||||
flagged: false
|
||||
actions:
|
||||
- kind: approve
|
||||
```
|
||||
@@ -27,19 +27,5 @@ Consult the [schema](https://json-schema.app/view/%23%2Fdefinitions%2FRecentActi
|
||||
|
||||
### Examples
|
||||
|
||||
* Free Karma Subreddits [YAML](/docs/subreddit/components/recentActivity/freeKarma.yaml) | [JSON](/docs/subreddit/components/recentActivity/freeKarma.json5) - Check if the Author has recently posted in any "free karma" subreddits
|
||||
* Submission in Free Karma Subreddits [YAML](/docs/subreddit/components/recentActivity/freeKarmaOnSubmission.yaml) | [JSON](/docs/subreddit/components/recentActivity/freeKarmaOnSubmission.json5) - Check if the Author has posted the Submission this check is running on in any "free karma" subreddits recently
|
||||
|
||||
# [Template Variables](/docs/subreddit/actionTemplating.md)
|
||||
|
||||
| Name | Description | Example |
|
||||
|----------------------|------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `result` | Summary of rule results (also found in Actioned Events) | 9 activities found in 2 of the specified subreddits (out of 21 total) MET threshold of >= 1 activities -- subreddits: SubredditA, SubredditB |
|
||||
| `window` | Number or duration of Activities considered from window | 100 activities |
|
||||
| `subSummary` | Comma-delimited list of subreddits matched by the criteria | SubredditA, SubredditB |
|
||||
| `subCount` | Number of subreddits that match the criteria | 2 |
|
||||
| `totalCount` | Total number of activities found by criteria | 9 |
|
||||
| `threshold` | The threshold used to trigger the rule | `>= 1` |
|
||||
| `karmaThreshold` | If present, the karma threshold used to trigger the rule | `> 5` |
|
||||
| `combinedKarma` | Total number of karma gained from the matched activities | 10 |
|
||||
| `subredditBreakdown` | A markdown list of filtered activities by subreddit | * SubredditA - 5 (71%) \n * Subreddit B - 2 (28%) |
|
||||
* Free Karma Subreddits [YAML](/docs/subreddit/componentscomponents/recentActivity/freeKarma.yaml) | [JSON](/docs/subreddit/componentscomponents/recentActivity/freeKarma.json5) - Check if the Author has recently posted in any "free karma" subreddits
|
||||
* Submission in Free Karma Subreddits [YAML](/docs/subreddit/componentscomponents/recentActivity/freeKarmaOnSubmission.yaml) | [JSON](/docs/subreddit/componentscomponents/recentActivity/freeKarmaOnSubmission.json5) - Check if the Author has posted the Submission this check is running on in any "free karma" subreddits recently
|
||||
|
||||
@@ -11,19 +11,12 @@ Which can then be used in conjunction with a [`window`](https://github.com/FoxxM
|
||||
|
||||
### Examples
|
||||
|
||||
* Trigger if regex matches against the current activity - [YAML](/docs/subreddit/components/regex/matchAnyCurrentActivity.yaml) | [JSON](/docs/subreddit/components/regex/matchAnyCurrentActivity.json5)
|
||||
* Trigger if regex matches 5 times against the current activity - [YAML](/docs/subreddit/components/regex/matchThresholdCurrentActivity.yaml) | [JSON](/docs/subreddit/components/regex/matchThresholdCurrentActivity.json5)
|
||||
* Trigger if regex matches against any part of a Submission - [YAML](/docs/subreddit/components/regex/matchSubmissionParts.yaml) | [JSON](/docs/subreddit/components/regex/matchSubmissionParts.json5)
|
||||
* Trigger if regex matches any of Author's last 10 activities - [YAML](/docs/subreddit/components/regex/matchHistoryActivity.yaml) | [JSON](/docs/subreddit/components/regex/matchHistoryActivity.json5)
|
||||
* Trigger if regex matches at least 3 of Author's last 10 activities - [YAML](/docs/subreddit/components/regex/matchActivityThresholdHistory.json5) | [JSON](/docs/subreddit/components/regex/matchActivityThresholdHistory.json5)
|
||||
* Trigger if there are 5 regex matches in the Author's last 10 activities - [YAML](/docs/subreddit/components/regex/matchTotalHistoryActivity.yaml) | [JSON](/docs/subreddit/components/regex/matchTotalHistoryActivity.json5)
|
||||
* Trigger if there are 5 regex matches in the Author's last 10 comments - [YAML](/docs/subreddit/components/regex/matchSubsetHistoryActivity.yaml) | [JSON](/docs/subreddit/components/regex/matchSubsetHistoryActivity.json5)
|
||||
* Remove comments that are spamming discord links - [YAML](/docs/subreddit/components/regex/removeDiscordSpam.yaml) | [JSON](/docs/subreddit/components/regex/removeDiscordSpam.json5)
|
||||
* Trigger if regex matches against the current activity - [YAML](/docs/subreddit/componentscomponents/regex/matchAnyCurrentActivity.yaml) | [JSON](/docs/subreddit/componentscomponents/regex/matchAnyCurrentActivity.json5)
|
||||
* Trigger if regex matches 5 times against the current activity - [YAML](/docs/subreddit/componentscomponents/regex/matchThresholdCurrentActivity.yaml) | [JSON](/docs/subreddit/componentscomponents/regex/matchThresholdCurrentActivity.json5)
|
||||
* Trigger if regex matches against any part of a Submission - [YAML](/docs/subreddit/componentscomponents/regex/matchSubmissionParts.yaml) | [JSON](/docs/subreddit/componentscomponents/regex/matchSubmissionParts.json5)
|
||||
* Trigger if regex matches any of Author's last 10 activities - [YAML](/docs/subreddit/componentscomponents/regex/matchHistoryActivity.yaml) | [JSON](/docs/subreddit/componentscomponents/regex/matchHistoryActivity.json5)
|
||||
* Trigger if regex matches at least 3 of Author's last 10 activities - [YAML](/docs/subreddit/componentscomponents/regex/matchActivityThresholdHistory.json5) | [JSON](/docs/subreddit/componentscomponents/regex/matchActivityThresholdHistory.json5)
|
||||
* Trigger if there are 5 regex matches in the Author's last 10 activities - [YAML](/docs/subreddit/componentscomponents/regex/matchTotalHistoryActivity.yaml) | [JSON](/docs/subreddit/componentscomponents/regex/matchTotalHistoryActivity.json5)
|
||||
* Trigger if there are 5 regex matches in the Author's last 10 comments - [YAML](/docs/subreddit/componentscomponents/regex/matchSubsetHistoryActivity.yaml) | [JSON](/docs/subreddit/componentscomponents/regex/matchSubsetHistoryActivity.json5)
|
||||
* Remove comments that are spamming discord links - [YAML](/docs/subreddit/componentscomponents/regex/removeDiscordSpam.yaml) | [JSON](/docs/subreddit/componentscomponents/regex/removeDiscordSpam.json5)
|
||||
* Differs from just using automod because this config can allow one-off/organic links from users who DO NOT spam discord links but will still remove the comment if the user is spamming them
|
||||
|
||||
# [Template Variables](/docs/subreddit/actionTemplating.md)
|
||||
|
||||
| Name | Description | Example |
|
||||
|---------------|---------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `result` | Summary of rule results (also found in Actioned Events) | Criteria 1 ✓ -- Activity Match ✓ => 1 > 0 (Threshold > 0) and 1 Total Matches (Window: 1 Item) -- Matched Values: "example.com/test" |
|
||||
| `matchSample` | A comma-delimited list of matches from activities | "example.com/test" |
|
||||
|
||||
@@ -47,16 +47,5 @@ With only `gapAllowance: 2` this rule **would trigger** because the the 1 and 2
|
||||
|
||||
## Examples
|
||||
|
||||
* Crosspost Spamming [JSON](/docs/subreddit/components/repeatActivity/crosspostSpamming.json5) | [YAML](/docs/subreddit/components/repeatActivity/crosspostSpamming.yaml) - Check if an Author is spamming their Submissions across multiple subreddits
|
||||
* Burst-posting [JSON](/docs/subreddit/components/repeatActivity/burstPosting.json5) | [YAML](/docs/subreddit/components/repeatActivity/burstPosting.yaml) - Check if Author is crossposting their Submissions in short bursts
|
||||
|
||||
# [Template Variables](/docs/subreddit/actionTemplating.md)
|
||||
|
||||
| Name | Description | Example |
|
||||
|-----------------------|---------------------------------------------------------|-------------------------------------------------------------|
|
||||
| `result` | Summary of rule results (also found in Actioned Events) | 1 of 1 unique items repeated >= 7 times, largest repeat: 22 |
|
||||
| `window` | Number or duration of Activities considered from window | 100 activities |
|
||||
| `threshold` | Number of repeats that trigger rule | `>= 7` |
|
||||
| `totalTriggeringSets` | Number of sets of repeats that matched threshold | 1 |
|
||||
| `largestRepeat` | The largest number of repeats in a single set | 22 |
|
||||
| `gapAllowance` | Number of non-repeat activities allowed between repeats | 2 |
|
||||
* Crosspost Spamming [JSON](/docs/subreddit/componentscomponents/repeatActivity/crosspostSpamming.json5) | [YAML](/docs/subreddit/componentscomponents/repeatActivity/crosspostSpamming.yaml) - Check if an Author is spamming their Submissions across multiple subreddits
|
||||
* Burst-posting [JSON](/docs/subreddit/componentscomponents/repeatActivity/burstPosting.json5) | [YAML](/docs/subreddit/componentscomponents/repeatActivity/burstPosting.yaml) - Check if Author is crossposting their Submissions in short bursts
|
||||
|
||||
@@ -267,15 +267,6 @@ When the rule is run in a **Comment Check** you may specify text comparisons (li
|
||||
* **minWordCount** -- The minimum number of words a comment must have
|
||||
* **caseSensitive** -- If the match comparison should be case-sensitive (defaults to `false`)
|
||||
|
||||
# [Template Variables](/docs/subreddit/actionTemplating.md)
|
||||
|
||||
|
||||
| Name | Description | Example |
|
||||
|-------------------|--------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `result` | Summary of rule results (also found in Actioned Events) | Searched top 0 comments in top 10 most popular submissions, 50 Youtube comments and found 2 reposts. --- Closest Match => >> The thought of this is terrifying << from Youtube (https://youtube.com/watch?v=example) with 100.00% sameness. |
|
||||
| `closestSummary` | If rule was triggered, the reposted activity type and where it came from | matched a comment from youtube |
|
||||
| `closestSameness` | If rule was triggered, the sameness of repost to the current activity | 100% |
|
||||
|
||||
# Examples
|
||||
|
||||
Examples of a *full* CM configuration, including the Repost Rule, in various scenarios. In each scenario the parts of the configuration that affect the rule are indicated.
|
||||
|
||||
@@ -181,16 +181,3 @@ rules:
|
||||
actions:
|
||||
- kind: remove
|
||||
```
|
||||
|
||||
# [Template Variables](/docs/subreddit/actionTemplating.md)
|
||||
|
||||
| Name | Description | Example |
|
||||
|---------------------------|--------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------|
|
||||
| `result` | Summary of rule results (also found in Actioned Events) | Current Activity Sentiment -0.35 (-0.45) PASSED sentiment test < -0.3 |
|
||||
| `triggered` | Boolean if rule was triggered or not | true |
|
||||
| `sentimentTest` | The sentiment value test | `< -0.3` |
|
||||
| `historicalSentimentTest` | The sentiment value test used for historical activities | `< -0.3` |
|
||||
| `averageScore` | The averaged score (equal weights) for all sentiment analysis tests run on the current activity | -0.35 |
|
||||
| `averageWindowScore` | The averaged score (equal weights) for all sentiment analysis tests run on historical activities | -0.35 |
|
||||
| `window` | Number or duration of Activities considered from window | 100 activities |
|
||||
| `totalMatching` | Number of activities that passed the sentimentTest | 1 |
|
||||
|
||||
78
docs/subreddit/components/subredditReady/README.md
Normal file
@@ -0,0 +1,78 @@
|
||||
Provided here are **complete, ready-to-go configuration** that can copy-pasted straight into your configuration wiki page to get going with ContextMod immediately.
|
||||
|
||||
These configurations attempt to provide sensible, non-destructive, default behavior for some common scenarios and subreddit types.
|
||||
|
||||
In most cases these will perform decently out-of-the-box but they are not perfect. You should still monitor bot behavior to see how it performs and will most likely still need to tweak these configurations to get your desired behavior.
|
||||
|
||||
All actions for these configurations are non-destructive in that:
|
||||
|
||||
* All instances where an activity would be modified (remove/ban/approve) will have `dryRun: true` set to prevent the action from actually being performed
|
||||
* These instances will also have a `report` action detailing the action would have been performed
|
||||
|
||||
**You will have to remove the `report` action and `dryRun` settings yourself.** This is to ensure that you understand the behavior the bot will be performing. If you are unsure of this you should leave them in place until you are certain the behavior the bot is performing is acceptable.
|
||||
|
||||
**YAML** is the same format as **automoderator**
|
||||
|
||||
## Submission-based Behavior
|
||||
|
||||
### Remove submissions from users who have used 'freekarma' subs to bypass karma checks
|
||||
|
||||
[YAML](/docs/subreddit/componentscomponents/subredditReady/freekarma.yaml) | [JSON](/docs/subreddit/componentscomponents/subredditReady/freekarma.json5)
|
||||
|
||||
If the user has any activity (comment/submission) in known freekarma subreddits in the past (50 activities or 6 months) then remove the submission.
|
||||
|
||||
### Remove submissions from users who have crossposted the same submission 4 or more times
|
||||
|
||||
[YAML](/docs/subreddit/componentscomponents/subredditReady/crosspostSpam.yaml) | [JSON](/docs/subreddit/componentscomponents/subredditReady/crosspostSpam.yaml)
|
||||
|
||||
If the user has crossposted the same submission in the past (50 activities or 6 months) 4 or more times in a row then remove the submission.
|
||||
|
||||
### Remove submissions from users who have crossposted or used 'freekarma' subs
|
||||
|
||||
[YAML](/docs/subreddit/componentscomponents/subredditReady/freeKarmaOrCrosspostSpam.yaml) | [JSON](/docs/subreddit/componentscomponents/subredditReady/freeKarmaOrCrosspostSpam.json5)
|
||||
|
||||
Will remove submission if either of the above two behaviors is detected
|
||||
|
||||
### Remove link submissions where the user's history is comprised of 10% or more of the same link
|
||||
|
||||
[YAML](/docs/subreddit/componentscomponents/subredditReady/selfPromo.yaml) | [JSON](/docs/subreddit/componentscomponents/subredditReady/selfPromo.json5)
|
||||
|
||||
If the link origin (youtube author, twitter author, etc. or regular domain for non-media links)
|
||||
|
||||
* comprises 10% or more of the users **entire** history in the past (100 activities or 6 months)
|
||||
* or comprises 10% or more of the users **submission** history in the past (100 activities or 6 months) and the user has low engagement (<50% of history is comments or 40%> of comment are as OP)
|
||||
|
||||
then remove the submission
|
||||
|
||||
## Comment-based behavior
|
||||
|
||||
### Remove comment if the user has posted the same comment 4 or more times in a row
|
||||
|
||||
[YAML](/docs/subreddit/componentscomponents/subredditReady/commentSpam.yaml) | [JSON](/docs/subreddit/componentscomponents/subredditReady/commentSpam.json5)
|
||||
|
||||
If the user made the same comment (with some fuzzy matching) 4 or more times in a row in the past (50 activities or 6 months) then remove the comment.
|
||||
|
||||
### Remove comment if it is discord invite link spam
|
||||
|
||||
[YAML](/docs/subreddit/componentscomponents/subredditReady/discordSpam.yaml) | [JSON](/docs/subreddit/componentscomponents/subredditReady/discordSpam.json5)
|
||||
|
||||
This rule goes a step further than automod can by being more discretionary about how it handles this type of spam.
|
||||
|
||||
* Remove the comment and **ban a user** if:
|
||||
* Comment being checked contains **only** a discord link (no other text) AND
|
||||
* Discord links appear **anywhere** in three or more of the last 10 comments the Author has made
|
||||
|
||||
otherwise...
|
||||
|
||||
* Remove the comment if:
|
||||
* Comment being checked contains **only** a discord link (no other text) OR
|
||||
* Comment contains a discord link **anywhere** AND
|
||||
* Discord links appear **anywhere** in three or more of the last 10 comments the Author has made
|
||||
|
||||
Using these checks ContextMod can more easily distinguish between these use cases for a user commenting with a discord link:
|
||||
|
||||
* actual spammers who only spam a discord link
|
||||
* users who may comment with a link but have context for it either in the current comment or in their history
|
||||
* users who many comment with a link but it's a one-off event (no other links historically)
|
||||
|
||||
Additionally, you could modify both/either of these checks to not remove one-off discord link comments but still remove if the user has a historical trend for spamming links
|
||||
46
docs/subreddit/components/subredditReady/commentSpam.json5
Normal file
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"polling": ["newComm"],
|
||||
"runs": [
|
||||
{
|
||||
"checks": [
|
||||
{
|
||||
//
|
||||
// Stop users who spam the same comment many times
|
||||
//
|
||||
// Remove a COMMENT if the user has crossposted it at least 4 times in recent history
|
||||
//
|
||||
"name": "low xp comment spam",
|
||||
"description": "X-posted comment >=4x",
|
||||
"kind": "comment",
|
||||
"condition": "AND",
|
||||
"rules": [
|
||||
{
|
||||
"name": "xPostLow",
|
||||
"kind": "repeatActivity",
|
||||
"gapAllowance": 2,
|
||||
"threshold": ">= 4",
|
||||
"window": {
|
||||
"count": 50,
|
||||
"duration": "6 months"
|
||||
}
|
||||
},
|
||||
],
|
||||
"actions": [
|
||||
// remove this after confirming behavior is acceptable
|
||||
{
|
||||
"kind": "report",
|
||||
"content": "Remove=> Posted same comment {{rules.xpostlow.largestRepeat}}x times"
|
||||
},
|
||||
//
|
||||
//
|
||||
{
|
||||
"kind": "remove",
|
||||
// remove the line below after confirming behavior is acceptable
|
||||
"dryRun": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
}
|
||||
@@ -1,18 +1,14 @@
|
||||
#polling:
|
||||
# - newComm
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Remove comments by users who spam the same comment many times
|
||||
#
|
||||
polling:
|
||||
- newComm
|
||||
runs:
|
||||
- checks:
|
||||
# Stop users who spam the same comment many times
|
||||
- name: low xp comment spam
|
||||
description: X-posted comment >=4x
|
||||
kind: comment
|
||||
condition: AND
|
||||
rules:
|
||||
- name: xPostLowComm
|
||||
- name: xPostLow
|
||||
kind: repeatActivity
|
||||
# number of "non-repeat" comments allowed between "repeat comments"
|
||||
gapAllowance: 2
|
||||
@@ -20,13 +16,11 @@
|
||||
threshold: '>= 4'
|
||||
# retrieve either last 50 comments or 6 months' of history, whichever is less
|
||||
window:
|
||||
count: 100
|
||||
count: 50
|
||||
duration: 6 months
|
||||
actions:
|
||||
- kind: report
|
||||
enable: false
|
||||
content: 'Remove => Posted same comment {{rules.xpostlowcomm.largestRepeat}}x times'
|
||||
|
||||
enable: true
|
||||
content: 'Remove => Posted same comment {{rules.xpostlow.largestRepeat}}x times'
|
||||
- kind: remove
|
||||
enable: true
|
||||
note: 'Posted same comment {{rules.xpostlowcomm.largestRepeat}}x times'
|
||||
81
docs/subreddit/components/subredditReady/crosspostSpam.json5
Normal file
@@ -0,0 +1,81 @@
|
||||
{
|
||||
"polling": ["unmoderated"],
|
||||
"runs": [
|
||||
{
|
||||
"checks": [
|
||||
{
|
||||
//
|
||||
// Stop users who post low-effort, crossposted spam
|
||||
//
|
||||
// Remove a SUBMISSION if the user has crossposted it at least 4 times in recent history AND
|
||||
// less than 50% of their activity is comments OR more than 40% of those comments are as OP (in the own submissions)
|
||||
//
|
||||
"name": "low xp spam and engagement",
|
||||
"description": "X-posted 4x and low comment engagement",
|
||||
"kind": "submission",
|
||||
"itemIs": [
|
||||
{
|
||||
"removed": false
|
||||
}
|
||||
],
|
||||
"condition": "AND",
|
||||
"rules": [
|
||||
{
|
||||
"name": "xPostLow",
|
||||
"kind": "repeatActivity",
|
||||
"gapAllowance": 2,
|
||||
"threshold": ">= 4",
|
||||
"window": {
|
||||
"count": 50,
|
||||
"duration": "6 months"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "lowOrOpComm",
|
||||
"kind": "history",
|
||||
"criteriaJoin": "OR",
|
||||
"criteria": [
|
||||
{
|
||||
"window": {
|
||||
"count": 100,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"comment": "< 50%"
|
||||
},
|
||||
{
|
||||
"window": {
|
||||
"count": 100,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"comment": "> 40% OP"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
// remove this after confirming behavior is acceptable
|
||||
{
|
||||
"kind": "report",
|
||||
"content": "Remove=>{{rules.xpostlow.largestRepeat}} X-P => {{rules.loworopcomm.thresholdSummary}}"
|
||||
},
|
||||
//
|
||||
//
|
||||
{
|
||||
"kind": "remove",
|
||||
// remove the line below after confirming behavior is acceptable
|
||||
"dryRun": true
|
||||
},
|
||||
// optionally remove "dryRun" from below if you want to leave a comment on removal
|
||||
// PROTIP: the comment is bland, you should make it better
|
||||
{
|
||||
"kind": "comment",
|
||||
"content": "Your submission has been removed because you cross-posted it {{rules.xpostlow.largestRepeat}} times and you have very low engagement outside of making submissions",
|
||||
"distinguish": true,
|
||||
"dryRun": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
}
|
||||
@@ -1,11 +1,7 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
polling:
|
||||
- unmoderated
|
||||
runs:
|
||||
- checks:
|
||||
# stop users who post low-effort, crossposted spam submissions
|
||||
#
|
||||
# Remove a SUBMISSION if the user has crossposted it at least 4 times in recent history AND
|
||||
@@ -22,7 +18,7 @@
|
||||
gapAllowance: 2
|
||||
threshold: '>= 4'
|
||||
window:
|
||||
count: 100
|
||||
count: 50
|
||||
duration: 6 months
|
||||
- name: lowOrOpComm
|
||||
kind: history
|
||||
@@ -38,15 +34,12 @@
|
||||
comment: '> 40% OP'
|
||||
actions:
|
||||
- kind: report
|
||||
enable: false
|
||||
enable: true
|
||||
content: >-
|
||||
Remove=>{{rules.xpostlow.largestRepeat}} X-P =>
|
||||
{{rules.loworopcomm.thresholdSummary}}
|
||||
|
||||
- kind: remove
|
||||
enable: true
|
||||
note: 'Repeated submission {{rules.xpostlow.largestRepeat}}x and low comment engagement'
|
||||
|
||||
- kind: comment
|
||||
enable: true
|
||||
content: >-
|
||||
79
docs/subreddit/components/subredditReady/discordSpam.json5
Normal file
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"polling": ["newComm"],
|
||||
"runs": [
|
||||
{
|
||||
"checks": [
|
||||
{
|
||||
"name": "ban discord only spammer",
|
||||
"description": "ban a user who spams only a discord link many times historically",
|
||||
"kind": "comment",
|
||||
"condition": "AND",
|
||||
"rules": [
|
||||
"linkOnlySpam",
|
||||
"linkAnywhereHistoricalSpam",
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"kind": "remove"
|
||||
},
|
||||
{
|
||||
"kind": "ban",
|
||||
"content": "spamming discord links"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "remove discord spam",
|
||||
"description": "remove comments from users who only link to discord or mention discord link many times historically",
|
||||
"kind": "comment",
|
||||
"condition": "OR",
|
||||
"rules": [
|
||||
{
|
||||
"name": "linkOnlySpam",
|
||||
"kind": "regex",
|
||||
"criteria": [
|
||||
{
|
||||
"name": "only link",
|
||||
"regex": "/^.*(discord\\.gg\\/[\\w\\d]+)$/i",
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"condition": "AND",
|
||||
"rules": [
|
||||
{
|
||||
"name": "linkAnywhereSpam",
|
||||
"kind": "regex",
|
||||
"criteria": [
|
||||
{
|
||||
"name": "contains link anywhere",
|
||||
"regex": "/^.*(discord\\.gg\\/[\\w\\d]+).*$/i",
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "linkAnywhereHistoricalSpam",
|
||||
"kind": "regex",
|
||||
"criteria": [
|
||||
{
|
||||
"name": "contains links anywhere historically",
|
||||
"regex": "/^.*(discord\\.gg\\/[\\w\\d]+).*$/i",
|
||||
"totalMatchThreshold": ">= 3",
|
||||
"lookAt": "comments",
|
||||
"window": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"kind": "remove"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
}
|
||||
@@ -1,18 +1,9 @@
|
||||
#polling:
|
||||
# - newComm
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
#
|
||||
# Remove comments from users who spam discord and telegram links
|
||||
# -- differs from just using automod:
|
||||
# 1) removes comment if it is ONLY discord/telegram link
|
||||
# 2) if not *only* link then checks user's history to see if link is spammed many times and only removes if it is
|
||||
#
|
||||
- name: ban chat only spammer
|
||||
description: ban a user who spams only a chat link many times historically
|
||||
polling:
|
||||
- newComm
|
||||
runs:
|
||||
- checks:
|
||||
- name: ban discord only spammer
|
||||
description: ban a user who spams only a discord link many times historically
|
||||
kind: comment
|
||||
condition: AND
|
||||
rules:
|
||||
@@ -22,9 +13,9 @@
|
||||
- kind: remove
|
||||
- kind: ban
|
||||
content: spamming discord links
|
||||
- name: remove chat spam
|
||||
- name: remove discord spam
|
||||
description: >-
|
||||
remove comments from users who only link to chat or mention chat
|
||||
remove comments from users who only link to discord or mention discord
|
||||
link many times historically
|
||||
kind: comment
|
||||
condition: OR
|
||||
@@ -33,9 +24,8 @@
|
||||
kind: regex
|
||||
criteria:
|
||||
- name: only link
|
||||
# https://regexr.com/70j9m
|
||||
# single quotes are required to escape special characters
|
||||
regex: '/^\s*((?:discord\.gg|t\.me|telegram\.me|telegr\.im)\/[\w\d]+)\s*$/i'
|
||||
regex: '/^.*(discord\.gg\/[\w\d]+)$/i'
|
||||
- condition: AND
|
||||
rules:
|
||||
- name: linkAnywhereSpam
|
||||
@@ -43,16 +33,15 @@
|
||||
criteria:
|
||||
- name: contains link anywhere
|
||||
# single quotes are required to escape special characters
|
||||
regex: '/((?:discord\.gg|t\.me|telegram\.me|telegr\.im)\/[\w\d]+)/i'
|
||||
regex: '/^.*(discord\.gg\/[\w\d]+).*$/i'
|
||||
- name: linkAnywhereHistoricalSpam
|
||||
kind: regex
|
||||
criteria:
|
||||
- name: contains links anywhere historically
|
||||
# single quotes are required to escape special characters
|
||||
regex: '/((?:discord\.gg|t\.me|telegram\.me|telegr\.im)\/[\w\d]+)/i'
|
||||
regex: '/^.*(discord\.gg\/[\w\d]+).*$/i'
|
||||
totalMatchThreshold: '>= 3'
|
||||
lookAt: comments
|
||||
window: 100
|
||||
window: 10
|
||||
actions:
|
||||
- kind: remove
|
||||
note: Chat spam link
|
||||
@@ -0,0 +1,142 @@
|
||||
{
|
||||
"polling": [
|
||||
"unmoderated"
|
||||
],
|
||||
"runs": [
|
||||
{
|
||||
"checks": [
|
||||
{
|
||||
//
|
||||
// Stop users who post low-effort, crossposted spam
|
||||
//
|
||||
// Remove a SUBMISSION if the user has crossposted it at least 4 times in recent history AND
|
||||
// less than 50% of their activity is comments OR more than 40% of those comments are as OP (in the own submissions)
|
||||
//
|
||||
"name": "remove on low xp spam and engagement",
|
||||
"description": "X-posted 4x and low comment engagement",
|
||||
"kind": "submission",
|
||||
"itemIs": [
|
||||
{
|
||||
"removed": false
|
||||
}
|
||||
],
|
||||
"condition": "AND",
|
||||
"rules": [
|
||||
{
|
||||
"name": "xPostLow",
|
||||
"kind": "repeatActivity",
|
||||
"gapAllowance": 2,
|
||||
"threshold": ">= 4",
|
||||
"window": {
|
||||
"count": 50,
|
||||
"duration": "6 months"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "lowOrOpComm",
|
||||
"kind": "history",
|
||||
"criteriaJoin": "OR",
|
||||
"criteria": [
|
||||
{
|
||||
"window": {
|
||||
"count": 100,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"comment": "< 50%"
|
||||
},
|
||||
{
|
||||
"window": {
|
||||
"count": 100,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"comment": "> 40% OP"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
// remove this after confirming behavior is acceptable
|
||||
{
|
||||
"kind": "report",
|
||||
"content": "Remove=>{{rules.xpostlow.largestRepeat}} X-P => {{rules.loworopcomm.thresholdSummary}}"
|
||||
},
|
||||
//
|
||||
//
|
||||
{
|
||||
"kind": "remove",
|
||||
// remove the line below after confirming behavior is acceptable
|
||||
"dryRun": true
|
||||
},
|
||||
// optionally remove "dryRun" from below if you want to leave a comment on removal
|
||||
// PROTIP: the comment is bland, you should make it better
|
||||
{
|
||||
"kind": "comment",
|
||||
"content": "Your submission has been removed because you cross-posted it {{rules.xpostlow.largestRepeat}} times and you have very low engagement outside of making submissions",
|
||||
"distinguish": true,
|
||||
"dryRun": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
//
|
||||
// Remove submissions from users who have recent activity in freekarma subs within the last 50 activities or 6 months (whichever is less)
|
||||
//
|
||||
"name": "freekarma removal",
|
||||
"description": "Remove submission if user has used freekarma sub recently",
|
||||
"kind": "submission",
|
||||
"itemIs": [
|
||||
{
|
||||
"removed": false
|
||||
}
|
||||
],
|
||||
"condition": "AND",
|
||||
"rules": [
|
||||
{
|
||||
"name": "freekarma",
|
||||
"kind": "recentActivity",
|
||||
"window": {
|
||||
"count": 50,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"useSubmissionAsReference": false,
|
||||
"thresholds": [
|
||||
{
|
||||
"subreddits": [
|
||||
"FreeKarma4U",
|
||||
"FreeKarma4You",
|
||||
"KarmaStore",
|
||||
"promote",
|
||||
"shamelessplug",
|
||||
"upvote"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
// remove this after confirming behavior is acceptable
|
||||
{
|
||||
"kind": "report",
|
||||
"content": "Remove=> {{rules.newtube.totalCount}} activities in freekarma subs"
|
||||
},
|
||||
//
|
||||
//
|
||||
{
|
||||
"kind": "remove",
|
||||
// remove the line below after confirming behavior is acceptable
|
||||
"dryRun": true
|
||||
},
|
||||
// optionally remove "dryRun" from below if you want to leave a comment on removal
|
||||
// PROTIP: the comment is bland, you should make it better
|
||||
{
|
||||
"kind": "comment",
|
||||
"content": "Your submission has been removed because you have recent activity in 'freekarma' subs",
|
||||
"distinguish": true,
|
||||
"dryRun": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
polling:
|
||||
- unmoderated
|
||||
runs:
|
||||
- checks:
|
||||
# stop users who post low-effort, crossposted spam submissions
|
||||
#
|
||||
# Remove a SUBMISSION if the user has crossposted it at least 4 times in recent history AND
|
||||
# less than 50% of their activity is comments OR more than 40% of those comments are as OP (in the own submissions)
|
||||
- name: remove on low xp spam and engagement
|
||||
description: X-posted 4x and low comment engagement
|
||||
kind: submission
|
||||
itemIs:
|
||||
- removed: false
|
||||
condition: AND
|
||||
rules:
|
||||
- name: xPostLow
|
||||
kind: repeatActivity
|
||||
gapAllowance: 2
|
||||
threshold: '>= 4'
|
||||
window:
|
||||
count: 50
|
||||
duration: 6 months
|
||||
- name: lowOrOpComm
|
||||
kind: history
|
||||
criteriaJoin: OR
|
||||
criteria:
|
||||
- window:
|
||||
count: 100
|
||||
duration: 6 months
|
||||
comment: < 50%
|
||||
- window:
|
||||
count: 100
|
||||
duration: 6 months
|
||||
comment: '> 40% OP'
|
||||
actions:
|
||||
- kind: report
|
||||
enable: true
|
||||
content: >-
|
||||
Remove=>{{rules.xpostlow.largestRepeat}} X-P =>
|
||||
{{rules.loworopcomm.thresholdSummary}}
|
||||
- kind: remove
|
||||
enable: false
|
||||
- kind: comment
|
||||
enable: true
|
||||
content: >-
|
||||
Your submission has been removed because you cross-posted it
|
||||
{{rules.xpostlow.largestRepeat}} times and you have very low
|
||||
engagement outside of making submissions
|
||||
distinguish: true
|
||||
dryRun: true
|
||||
# Remove submissions from users who have recent activity in freekarma subs within the last 50 activities or 6 months (whichever is less)
|
||||
- name: freekarma removal
|
||||
description: Remove submission if user has used freekarma sub recently
|
||||
kind: submission
|
||||
itemIs:
|
||||
- removed: false
|
||||
condition: AND
|
||||
rules:
|
||||
- name: freekarma
|
||||
kind: recentActivity
|
||||
window:
|
||||
count: 50
|
||||
duration: 6 months
|
||||
useSubmissionAsReference: false
|
||||
thresholds:
|
||||
- subreddits:
|
||||
- FreeKarma4U
|
||||
- FreeKarma4You
|
||||
- KarmaStore
|
||||
- promote
|
||||
- shamelessplug
|
||||
- upvote
|
||||
actions:
|
||||
- kind: report
|
||||
enable: true
|
||||
content: 'Remove=> {{rules.newtube.totalCount}} activities in freekarma subs'
|
||||
- kind: remove
|
||||
enable: false
|
||||
- kind: comment
|
||||
enable: true
|
||||
content: >-
|
||||
Your submission has been removed because you have recent activity in
|
||||
'freekarma' subs
|
||||
distinguish: true
|
||||
dryRun: true
|
||||
68
docs/subreddit/components/subredditReady/freekarma.json5
Normal file
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"polling": [
|
||||
"unmoderated"
|
||||
],
|
||||
"runs": [
|
||||
{
|
||||
"checks": [
|
||||
{
|
||||
//
|
||||
// Remove submissions from users who have recent activity in freekarma subs within the last 50 activities or 6 months (whichever is less)
|
||||
//
|
||||
"name": "freekarma removal",
|
||||
"description": "Remove submission if user has used freekarma sub recently",
|
||||
"kind": "submission",
|
||||
"itemIs": [
|
||||
{
|
||||
"removed": false
|
||||
}
|
||||
],
|
||||
"condition": "AND",
|
||||
"rules": [
|
||||
{
|
||||
"name": "freekarma",
|
||||
"kind": "recentActivity",
|
||||
"window": {
|
||||
"count": 50,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"useSubmissionAsReference": false,
|
||||
"thresholds": [
|
||||
{
|
||||
"subreddits": [
|
||||
"FreeKarma4U",
|
||||
"FreeKarma4You",
|
||||
"KarmaStore",
|
||||
"upvote"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
// remove this after confirming behavior is acceptable
|
||||
{
|
||||
"kind": "report",
|
||||
"content": "Remove=> {{rules.newtube.totalCount}} activities in freekarma subs"
|
||||
},
|
||||
//
|
||||
//
|
||||
{
|
||||
"kind": "remove",
|
||||
// remove the line below after confirming behavior is acceptable
|
||||
"dryRun": true,
|
||||
},
|
||||
// optionally remove "dryRun" from below if you want to leave a comment on removal
|
||||
// PROTIP: the comment is bland, you should make it better
|
||||
{
|
||||
"kind": "comment",
|
||||
"content": "Your submission has been removed because you have recent activity in 'freekarma' subs",
|
||||
"distinguish": true,
|
||||
"dryRun": true,
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
}
|
||||
36
docs/subreddit/components/subredditReady/freekarma.yaml
Normal file
@@ -0,0 +1,36 @@
|
||||
polling:
|
||||
- unmoderated
|
||||
runs:
|
||||
- checks:
|
||||
# Remove submissions from users who have recent activity in freekarma subs within the last 50 activities or 6 months (whichever is less)
|
||||
- name: freekarma removal
|
||||
description: Remove submission if user has used freekarma sub recently
|
||||
kind: submission
|
||||
itemIs:
|
||||
- removed: false
|
||||
condition: AND
|
||||
rules:
|
||||
- name: freekarma
|
||||
kind: recentActivity
|
||||
window:
|
||||
count: 50
|
||||
duration: 6 months
|
||||
useSubmissionAsReference: false
|
||||
thresholds:
|
||||
- subreddits:
|
||||
- FreeKarma4U
|
||||
- FreeKarma4You
|
||||
- KarmaStore
|
||||
- upvote
|
||||
actions:
|
||||
- kind: report
|
||||
enable: true
|
||||
content: 'Remove=> {{rules.newtube.totalCount}} activities in freekarma subs'
|
||||
- kind: remove
|
||||
enable: true
|
||||
- kind: comment
|
||||
enable: false
|
||||
content: >-
|
||||
Your submission has been removed because you have recent activity in
|
||||
'freekarma' subs
|
||||
distinguish: true
|
||||
108
docs/subreddit/components/subredditReady/selfPromo.json5
Normal file
@@ -0,0 +1,108 @@
|
||||
{
|
||||
"polling": [
|
||||
"unmoderated"
|
||||
],
|
||||
"runs": [
|
||||
{
|
||||
"checks": [
|
||||
{
|
||||
//
|
||||
// Stop users who make link submissions with a self-promotional agenda (with reddit's suggested 10% rule)
|
||||
// https://www.reddit.com/wiki/selfpromotion#wiki_guidelines_for_self-promotion_on_reddit
|
||||
//
|
||||
// Remove a SUBMISSION if the link comprises more than or equal to 10% of users history (100 activities or 6 months) OR
|
||||
//
|
||||
// if link comprises 10% of submission history (100 activities or 6 months)
|
||||
// AND less than 50% of their activity is comments OR more than 40% of those comments are as OP (in the own submissions)
|
||||
//
|
||||
"name": "Self-promo all AND low engagement",
|
||||
"description": "Self-promo is >10% for all or just sub and low comment engagement",
|
||||
"kind": "submission",
|
||||
"condition": "OR",
|
||||
"rules": [
|
||||
{
|
||||
"name": "attr",
|
||||
"kind": "attribution",
|
||||
"criteria": [
|
||||
{
|
||||
"threshold": ">= 10%",
|
||||
"window": {
|
||||
"count": 100,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"domains": [
|
||||
"AGG:SELF"
|
||||
]
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"condition": "AND",
|
||||
"rules": [
|
||||
{
|
||||
"name": "attrsub",
|
||||
"kind": "attribution",
|
||||
"criteria": [
|
||||
{
|
||||
"threshold": ">= 10%",
|
||||
"thresholdOn": "submissions",
|
||||
"window": {
|
||||
"count": 100,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"domains": [
|
||||
"AGG:SELF"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "lowOrOpComm",
|
||||
"kind": "history",
|
||||
"criteriaJoin": "OR",
|
||||
"criteria": [
|
||||
{
|
||||
"window": {
|
||||
"count": 100,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"comment": "< 50%"
|
||||
},
|
||||
{
|
||||
"window": {
|
||||
"count": 100,
|
||||
"duration": "6 months"
|
||||
},
|
||||
"comment": "> 40% OP"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"kind": "report",
|
||||
"content": "{{rules.attr.largestPercent}}{{rules.attrsub.largestPercent}} of {{rules.attr.activityTotal}}{{rules.attrsub.activityTotal}} items ({{rules.attr.window}}{{rules.attrsub.window}}){{#rules.loworopcomm.thresholdSummary}} => {{rules.loworopcomm.thresholdSummary}}{{/rules.loworopcomm.thresholdSummary}}"
|
||||
},
|
||||
//
|
||||
//
|
||||
{
|
||||
"kind": "remove",
|
||||
// remove the line below after confirming behavior is acceptable
|
||||
"dryRun": true
|
||||
},
|
||||
// optionally remove "dryRun" from below if you want to leave a comment on removal
|
||||
// PROTIP: the comment is bland, you should make it better
|
||||
{
|
||||
"kind": "comment",
|
||||
"content": "Your submission has been removed it comprises 10% or more of your recent history ({{rules.attr.largestPercent}}{{rules.attrsub.largestPercent}}). This is against [reddit's self promotional guidelines.](https://www.reddit.com/wiki/selfpromotion#wiki_guidelines_for_self-promotion_on_reddit)",
|
||||
"distinguish": true,
|
||||
"dryRun": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
#polling:
|
||||
# - newSub
|
||||
#runs:
|
||||
# - checks:
|
||||
#### Uncomment the code above to use this as a FULL subreddit config
|
||||
####
|
||||
#### Otherwise copy-paste the code below to use as a CHECK
|
||||
polling:
|
||||
- unmoderated
|
||||
runs:
|
||||
- checks:
|
||||
#
|
||||
# Stop users who make link submissions with a self-promotional agenda (with reddit's suggested 10% rule)
|
||||
# https://www.reddit.com/wiki/selfpromotion#wiki_guidelines_for_self-promotion_on_reddit
|
||||
@@ -61,11 +58,8 @@
|
||||
({{rules.attr.window}}{{rules.attrsub.window}}){{#rules.loworopcomm.thresholdSummary}}
|
||||
=>
|
||||
{{rules.loworopcomm.thresholdSummary}}{{/rules.loworopcomm.thresholdSummary}}
|
||||
|
||||
- kind: remove
|
||||
enable: true
|
||||
note: '>10% of author's history is content from this creator'
|
||||
|
||||
enable: false
|
||||
- kind: comment
|
||||
enable: true
|
||||
content: >-
|
||||
@@ -75,3 +69,4 @@
|
||||
is against [reddit's self promotional
|
||||
guidelines.](https://www.reddit.com/wiki/selfpromotion#wiki_guidelines_for_self-promotion_on_reddit)
|
||||
distinguish: true
|
||||
dryRun: true
|
||||
@@ -24,7 +24,7 @@ Consult the [schema](https://json-schema.app/view/%23%2Fdefinitions%2FUserNoteCr
|
||||
|
||||
### Examples
|
||||
|
||||
* Do not tag user with Good User note [JSON](/docs/subreddit/components/userNotes/usernoteFilter.json5) | [YAML](/docs/subreddit/components/userNotes/usernoteFilter.yaml)
|
||||
* Do not tag user with Good User note [JSON](/docs/subreddit/componentscomponents/userNotes/usernoteFilter.json5) | [YAML](/docs/subreddit/componentscomponents/userNotes/usernoteFilter.yaml)
|
||||
|
||||
## Action
|
||||
|
||||
@@ -33,4 +33,4 @@ A User Note can also be added to the Author of a Submission or Comment with the
|
||||
|
||||
### Examples
|
||||
|
||||
* Add note on user doing self promotion [JSON](/docs/subreddit/components/userNotes/usernoteSP.json5) | [YAML](/docs/subreddit/components/userNotes/usernoteSP.yaml)
|
||||
* Add note on user doing self promotion [JSON](/docs/subreddit/componentscomponents/userNotes/usernoteSP.json5) | [YAML](/docs/subreddit/componentscomponents/userNotes/usernoteSP.yaml)
|
||||
|
||||
@@ -104,7 +104,7 @@ If you already have a configuration you may skip the below step and go directly
|
||||
|
||||
### Using an Example Config
|
||||
|
||||
Visit the [Examples](https://github.com/FoxxMD/context-mod/tree/master/docs/examples) folder to find various examples of individual rules or see the [subreddit cookbook examples.](/docs/subreddit/components/cookbook)
|
||||
Visit the [Examples](https://github.com/FoxxMD/context-mod/tree/master/docs/examples) folder to find various examples of individual rules or see the [subreddit-ready examples.](/docs/subreddit/components/subredditReady)
|
||||
|
||||
After you have found a configuration to use as a starting point:
|
||||
|
||||
|
||||
2010
package-lock.json
generated
13
package.json
@@ -21,7 +21,11 @@
|
||||
"circular-graph": "madge --image graph.svg --circular --extensions ts src/index.ts",
|
||||
"postinstall": "patch-package",
|
||||
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js",
|
||||
"initMigration": "npm run typeorm -- migration:generate -t 1642180264563 -d ormconfig.js \"src/Common/Migrations/Database/init\""
|
||||
"initMigration": "npm run typeorm -- migration:generate -t 1642180264563 -d ormconfig.js \"src/Common/Migrations/Database/init\"",
|
||||
"cv-install-ubuntu-prebuild": "build-opencv --incDir /usr/include/opencv4/ --libDir /lib/x86_64-linux-gnu/ --binDir=/usr/bin/ --nobuild rebuild",
|
||||
"cv-install-docker-prebuild": "build-opencv --incDir /usr/include/opencv4/ --libDir /usr/lib/ --binDir=/usr/bin/ --nobuild rebuild",
|
||||
"cv-autoinstall-cuda": "build-opencv --version 4.5.5 --flags=\"-DWITH_CUDA=ON -DWITH_CUDNN=ON -DOPENCV_DNN_CUDA=ON -DCUDA_FAST_MATH=ON\" build",
|
||||
"cv-autoinstall": "build-opencv build"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
@@ -31,10 +35,9 @@
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@awaitjs/express": "^0.8.0",
|
||||
"@datasert/cronjs-matcher": "^1.2.0",
|
||||
"@googleapis/youtube": "^2.0.0",
|
||||
"@influxdata/influxdb-client": "^1.31.0",
|
||||
"@influxdata/influxdb-client-apis": "^1.31.0",
|
||||
"@influxdata/influxdb-client": "^1.27.0",
|
||||
"@influxdata/influxdb-client-apis": "^1.27.0",
|
||||
"@nlpjs/core": "^4.23.4",
|
||||
"@nlpjs/lang-de": "^4.23.4",
|
||||
"@nlpjs/lang-en": "^4.23.4",
|
||||
@@ -43,6 +46,7 @@
|
||||
"@nlpjs/language": "^4.22.7",
|
||||
"@nlpjs/nlp": "^4.23.5",
|
||||
"@stdlib/regexp-regexp": "^0.0.6",
|
||||
"@u4/opencv4nodejs": "^6.2.1",
|
||||
"ajv": "^7.2.4",
|
||||
"ansi-regex": ">=5.0.1",
|
||||
"async": "^3.2.0",
|
||||
@@ -161,6 +165,7 @@
|
||||
"better-sqlite3": "^7.5.0",
|
||||
"mongo": "^3.6.0",
|
||||
"mysql": "^2.18.1",
|
||||
"opencv-build": "^0.1.9",
|
||||
"pg": "^8.7.1",
|
||||
"sharp": "^0.29.1"
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import LockAction, {LockActionJson} from "./LockAction";
|
||||
import {RemoveAction, RemoveActionJson} from "./RemoveAction";
|
||||
import {ReportAction, ReportActionJson} from "./ReportAction";
|
||||
import {FlairAction, FlairActionJson} from "./SubmissionAction/FlairAction";
|
||||
import Action, {ActionJson, ActionRuntimeOptions, StructuredActionJson} from "./index";
|
||||
import Action, {ActionJson, StructuredActionJson} from "./index";
|
||||
import {Logger} from "winston";
|
||||
import {UserNoteAction, UserNoteActionJson} from "./UserNoteAction";
|
||||
import ApproveAction, {ApproveActionConfig} from "./ApproveAction";
|
||||
@@ -21,38 +21,38 @@ import {ModNoteAction, ModNoteActionJson} from "./ModNoteAction";
|
||||
import {SubmissionAction, SubmissionActionJson} from "./SubmissionAction";
|
||||
|
||||
export function actionFactory
|
||||
(config: StructuredActionJson, runtimeOptions: ActionRuntimeOptions): Action {
|
||||
(config: StructuredActionJson, logger: Logger, subredditName: string, resources: SubredditResources, client: ExtendedSnoowrap, emitter: EventEmitter): Action {
|
||||
switch (config.kind) {
|
||||
case 'comment':
|
||||
return new CommentAction({...config as StructuredFilter<CommentActionJson>, ...runtimeOptions});
|
||||
return new CommentAction({...config as StructuredFilter<CommentActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'submission':
|
||||
return new SubmissionAction({...config as StructuredFilter<SubmissionActionJson>, ...runtimeOptions});
|
||||
return new SubmissionAction({...config as StructuredFilter<SubmissionActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'lock':
|
||||
return new LockAction({...config as StructuredFilter<LockActionJson>, ...runtimeOptions});
|
||||
return new LockAction({...config as StructuredFilter<LockActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'remove':
|
||||
return new RemoveAction({...config as StructuredFilter<RemoveActionJson>, ...runtimeOptions});
|
||||
return new RemoveAction({...config as StructuredFilter<RemoveActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'report':
|
||||
return new ReportAction({...config as StructuredFilter<ReportActionJson>, ...runtimeOptions});
|
||||
return new ReportAction({...config as StructuredFilter<ReportActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'flair':
|
||||
return new FlairAction({...config as StructuredFilter<FlairActionJson>, ...runtimeOptions});
|
||||
return new FlairAction({...config as StructuredFilter<FlairActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'userflair':
|
||||
return new UserFlairAction({...config as StructuredFilter<UserFlairActionJson>, ...runtimeOptions});
|
||||
return new UserFlairAction({...config as StructuredFilter<UserFlairActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'approve':
|
||||
return new ApproveAction({...config as StructuredFilter<ApproveActionConfig>, ...runtimeOptions});
|
||||
return new ApproveAction({...config as StructuredFilter<ApproveActionConfig>, logger, subredditName, resources, client, emitter});
|
||||
case 'usernote':
|
||||
return new UserNoteAction({...config as StructuredFilter<UserNoteActionJson>, ...runtimeOptions});
|
||||
return new UserNoteAction({...config as StructuredFilter<UserNoteActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'ban':
|
||||
return new BanAction({...config as StructuredFilter<BanActionJson>, ...runtimeOptions});
|
||||
return new BanAction({...config as StructuredFilter<BanActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'message':
|
||||
return new MessageAction({...config as StructuredFilter<MessageActionJson>, ...runtimeOptions});
|
||||
return new MessageAction({...config as StructuredFilter<MessageActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'dispatch':
|
||||
return new DispatchAction({...config as StructuredFilter<DispatchActionJson>, ...runtimeOptions});
|
||||
return new DispatchAction({...config as StructuredFilter<DispatchActionJson>, logger, subredditName, resources, client, emitter});
|
||||
case 'cancelDispatch':
|
||||
return new CancelDispatchAction({...config as StructuredFilter<CancelDispatchActionJson>, ...runtimeOptions})
|
||||
return new CancelDispatchAction({...config as StructuredFilter<CancelDispatchActionJson>, logger, subredditName, resources, client, emitter})
|
||||
case 'contributor':
|
||||
return new ContributorAction({...config as StructuredFilter<ContributorActionJson>, ...runtimeOptions})
|
||||
return new ContributorAction({...config as StructuredFilter<ContributorActionJson>, logger, subredditName, resources, client, emitter})
|
||||
case 'modnote':
|
||||
return new ModNoteAction({...config as StructuredFilter<ModNoteActionJson>, ...runtimeOptions})
|
||||
return new ModNoteAction({...config as StructuredFilter<ModNoteActionJson>, logger, subredditName, resources, client, emitter})
|
||||
default:
|
||||
throw new Error('rule "kind" was not recognized.');
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTarget, ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {asComment, asSubmission} from "../util";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class ApproveAction extends Action {
|
||||
|
||||
@@ -27,7 +26,7 @@ export class ApproveAction extends Action {
|
||||
this.targets = targets;
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
const touchedEntities = [];
|
||||
|
||||
|
||||
@@ -7,18 +7,10 @@ import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {truncateStringToLength} from "../util";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
const truncate = truncateStringToLength(100);
|
||||
const truncateLongMessage = truncateStringToLength(200);
|
||||
|
||||
const truncateIfNotUndefined = (val: string | undefined) => {
|
||||
if(val === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return truncate(val);
|
||||
}
|
||||
|
||||
export class BanAction extends Action {
|
||||
|
||||
message?: string;
|
||||
@@ -47,13 +39,13 @@ export class BanAction extends Action {
|
||||
return 'ban';
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
const renderedBody = await this.renderContent(this.message, item, ruleResults, actionResults);
|
||||
const renderedContent = renderedBody === undefined ? undefined : `${renderedBody}${await this.resources.renderFooter(item, this.footer)}`;
|
||||
const renderedBody = this.message === undefined ? undefined : await this.resources.renderContent(this.message, item, ruleResults);
|
||||
const renderedContent = renderedBody === undefined ? undefined : `${renderedBody}${await this.resources.generateFooter(item, this.footer)}`;
|
||||
|
||||
const renderedReason = truncateIfNotUndefined(await this.renderContent(this.reason, item, ruleResults, actionResults) as string);
|
||||
const renderedNote = truncateIfNotUndefined(await this.renderContent(this.note, item, ruleResults, actionResults) as string);
|
||||
const renderedReason = this.reason === undefined ? undefined : truncate(await this.resources.renderContent(this.reason, item, ruleResults));
|
||||
const renderedNote = this.note === undefined ? undefined : truncate(await this.resources.renderContent(this.note, item, ruleResults));
|
||||
|
||||
const touchedEntities = [];
|
||||
let banPieces = [];
|
||||
@@ -80,13 +72,7 @@ export class BanAction extends Action {
|
||||
dryRun,
|
||||
success: true,
|
||||
result: `Banned ${item.author.name} ${durText}${renderedReason !== undefined ? ` (${renderedReason})` : ''}`,
|
||||
touchedEntities,
|
||||
data: {
|
||||
message: renderedContent === undefined ? undefined : renderedContent,
|
||||
reason: renderedReason,
|
||||
note: renderedNote,
|
||||
duration: durText
|
||||
}
|
||||
touchedEntities
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import {isSubmission, parseDurationValToDuration} from "../util";
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTarget, ActionTypes, InclusiveActionTarget} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class CancelDispatchAction extends Action {
|
||||
identifiers?: (string | null)[];
|
||||
@@ -36,7 +35,7 @@ export class CancelDispatchAction extends Action {
|
||||
this.targets = !Array.isArray(target) ? [target] : target;
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
// see note in DispatchAction about missing runtimeDryrun
|
||||
const dryRun = this.dryRun;
|
||||
|
||||
|
||||
@@ -1,21 +1,14 @@
|
||||
import Action, {ActionJson, ActionOptions} from "./index";
|
||||
import {Comment, VoteableContent} from "snoowrap";
|
||||
import Submission from "snoowrap/dist/objects/Submission";
|
||||
import {activityIsRemoved, renderContent} from "../Utils/SnoowrapUtils";
|
||||
import {renderContent} from "../Utils/SnoowrapUtils";
|
||||
import {ActionProcessResult, Footer, RequiredRichContent, RichContent, RuleResult} from "../Common/interfaces";
|
||||
import {
|
||||
asComment,
|
||||
asSubmission,
|
||||
getActivitySubredditName,
|
||||
parseRedditThingsFromLink,
|
||||
truncateStringToLength
|
||||
} from "../util";
|
||||
import {asComment, asSubmission, parseRedditThingsFromLink, truncateStringToLength} from "../util";
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTarget, ActionTypes, ArbitraryActionTarget} from "../Common/Infrastructure/Atomic";
|
||||
import {CMError} from "../Utils/Errors";
|
||||
import {SnoowrapActivity} from "../Common/Infrastructure/Reddit";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class CommentAction extends Action {
|
||||
content: string;
|
||||
@@ -24,7 +17,6 @@ export class CommentAction extends Action {
|
||||
distinguish: boolean = false;
|
||||
footer?: false | string;
|
||||
targets: ArbitraryActionTarget[]
|
||||
asModTeam: boolean;
|
||||
|
||||
constructor(options: CommentActionOptions) {
|
||||
super(options);
|
||||
@@ -34,14 +26,12 @@ export class CommentAction extends Action {
|
||||
sticky = false,
|
||||
distinguish = false,
|
||||
footer,
|
||||
targets = ['self'],
|
||||
asModTeam = false,
|
||||
targets = ['self']
|
||||
} = options;
|
||||
this.footer = footer;
|
||||
this.content = content;
|
||||
this.lock = lock;
|
||||
this.sticky = sticky;
|
||||
this.asModTeam = asModTeam;
|
||||
this.distinguish = distinguish;
|
||||
if (!Array.isArray(targets)) {
|
||||
this.targets = [targets];
|
||||
@@ -54,11 +44,12 @@ export class CommentAction extends Action {
|
||||
return 'comment';
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
const body = await this.renderContent(this.content, item, ruleResults, actionResults) as string;
|
||||
const content = await this.resources.getContent(this.content, item.subreddit);
|
||||
const body = await renderContent(content, item, ruleResults, this.resources.userNotes);
|
||||
|
||||
const footer = await this.resources.renderFooter(item, this.footer);
|
||||
const footer = await this.resources.generateFooter(item, this.footer);
|
||||
|
||||
const renderedContent = `${body}${footer}`;
|
||||
this.logger.verbose(`Contents:\r\n${renderedContent.length > 100 ? `\r\n${renderedContent}` : renderedContent}`);
|
||||
@@ -113,48 +104,17 @@ export class CommentAction extends Action {
|
||||
continue;
|
||||
}
|
||||
|
||||
if(this.asModTeam) {
|
||||
if(!targetItem.can_mod_post) {
|
||||
const noMod = `[${targetIdentifier}] Cannot comment as subreddit because bot is not a moderator`;
|
||||
this.logger.warn(noMod);
|
||||
targetResults.push(noMod);
|
||||
continue;
|
||||
}
|
||||
if(getActivitySubredditName(targetItem) !== this.resources.subreddit.display_name) {
|
||||
const wrongSubreddit = `[${targetIdentifier}] Will not comment as subreddit because Activity did not occur in the same subreddit as the bot is moderating`;
|
||||
this.logger.warn(wrongSubreddit);
|
||||
targetResults.push(wrongSubreddit);
|
||||
continue;
|
||||
}
|
||||
if(!activityIsRemoved(targetItem)) {
|
||||
const notRemoved = `[${targetIdentifier}] Cannot comment as subreddit because Activity IS NOT REMOVED.`
|
||||
this.logger.warn(notRemoved);
|
||||
targetResults.push(notRemoved);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let modifiers = [];
|
||||
let reply: Comment;
|
||||
if (!dryRun) {
|
||||
if(this.asModTeam) {
|
||||
try {
|
||||
reply = await this.client.addRemovalMessage(targetItem, renderedContent, 'public_as_subreddit',{lock: this.lock});
|
||||
} catch (e: any) {
|
||||
this.logger.warn(new CMError('Could not comment as subreddit', {cause: e}));
|
||||
targetResults.push(`Could not comment as subreddit: ${e.message}`);
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// @ts-ignore
|
||||
reply = await targetItem.reply(renderedContent);
|
||||
}
|
||||
// @ts-ignore
|
||||
reply = await targetItem.reply(renderedContent);
|
||||
// add to recent so we ignore activity when/if it is discovered by polling
|
||||
await this.resources.setRecentSelf(reply);
|
||||
touchedEntities.push(reply);
|
||||
}
|
||||
|
||||
if (!this.asModTeam && this.lock && targetItem.can_mod_post) {
|
||||
if (this.lock && targetItem.can_mod_post) {
|
||||
if (!targetItem.can_mod_post) {
|
||||
this.logger.warn(`[${targetIdentifier}] Cannot lock because bot is not a moderator`);
|
||||
} else {
|
||||
@@ -167,7 +127,7 @@ export class CommentAction extends Action {
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.asModTeam && this.distinguish) {
|
||||
if (this.distinguish) {
|
||||
if (!targetItem.can_mod_post) {
|
||||
this.logger.warn(`[${targetIdentifier}] Cannot lock Distinguish/Sticky because bot is not a moderator`);
|
||||
} else {
|
||||
@@ -194,12 +154,6 @@ export class CommentAction extends Action {
|
||||
success: !allErrors,
|
||||
result: `${targetResults.join('\n')}${truncateStringToLength(100)(body)}`,
|
||||
touchedEntities,
|
||||
data: {
|
||||
body,
|
||||
bodyShort: truncateStringToLength(100)(body),
|
||||
comments: targetResults,
|
||||
commentsFormatted: targetResults.map(x => `* ${x}`).join('\n')
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -243,16 +197,6 @@ export interface CommentActionConfig extends RequiredRichContent, Footer {
|
||||
* If target is not self/parent then CM assumes the value is a reddit permalink and will attempt to make a comment to that Activity
|
||||
* */
|
||||
targets?: ArbitraryActionTarget | ArbitraryActionTarget[]
|
||||
|
||||
/**
|
||||
* Comment "as subreddit" using the "/u/subreddit-ModTeam" account
|
||||
*
|
||||
* RESTRICTIONS:
|
||||
*
|
||||
* * Target activity must ALREADY BE REMOVED
|
||||
* * Will always distinguish and sticky the created comment
|
||||
* */
|
||||
asModTeam?: boolean
|
||||
}
|
||||
|
||||
export interface CommentActionOptions extends CommentActionConfig, ActionOptions {
|
||||
|
||||
@@ -7,7 +7,6 @@ import Comment from "snoowrap/dist/objects/Comment";
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTarget, ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class ContributorAction extends Action {
|
||||
|
||||
@@ -26,7 +25,7 @@ export class ContributorAction extends Action {
|
||||
this.actionType = action;
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
|
||||
const contributors = await this.resources.getSubredditContributors();
|
||||
|
||||
@@ -8,7 +8,6 @@ import {activityDispatchConfigToDispatch, isSubmission, parseDurationValToDurati
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTarget, ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class DispatchAction extends Action {
|
||||
dispatchData: ActivityDispatchConfig;
|
||||
@@ -40,7 +39,7 @@ export class DispatchAction extends Action {
|
||||
this.targets = !Array.isArray(target) ? [target] : target;
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
// ignore runtimeDryrun here because "real run" isn't causing any reddit api calls to happen
|
||||
// -- basically if bot is in dryrun this should still run since we want the "full effect" of the bot
|
||||
// BUT if the action explicitly sets 'dryRun: true' then do not dispatch as they probably don't want to it actually going (intention?)
|
||||
|
||||
@@ -5,14 +5,13 @@ import {ActionProcessResult, RuleResult} from "../Common/interfaces";
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class LockAction extends Action {
|
||||
getKind(): ActionTypes {
|
||||
return 'lock';
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
const touchedEntities = [];
|
||||
//snoowrap typing issue, thinks comments can't be locked
|
||||
|
||||
@@ -16,7 +16,6 @@ import {ErrorWithCause} from "pony-cause";
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class MessageAction extends Action {
|
||||
content: string;
|
||||
@@ -49,30 +48,28 @@ export class MessageAction extends Action {
|
||||
return 'message';
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
|
||||
const body = await this.renderContent(this.content, item, ruleResults, actionResults);
|
||||
const titleTemplate = this.title ?? `Concerning your ${isSubmission(item) ? 'Submission' : 'Comment'}`;
|
||||
const subject = await this.renderContent(titleTemplate, item, ruleResults, actionResults) as string;
|
||||
const body = await this.resources.renderContent(this.content, item, ruleResults);
|
||||
const subject = this.title === undefined ? `Concerning your ${isSubmission(item) ? 'Submission' : 'Comment'}` : await this.resources.renderContent(this.title, item, ruleResults);
|
||||
|
||||
const footer = await this.resources.renderFooter(item, this.footer);
|
||||
const footer = await this.resources.generateFooter(item, this.footer);
|
||||
|
||||
const renderedContent = `${body}${footer}`;
|
||||
|
||||
let recipient = item.author.name;
|
||||
if(this.to !== undefined) {
|
||||
const renderedTo = await this.renderContent(this.to, item, ruleResults, actionResults) as string;
|
||||
// parse to value
|
||||
try {
|
||||
const entityData = parseRedditEntity(renderedTo, 'user');
|
||||
const entityData = parseRedditEntity(this.to, 'user');
|
||||
if(entityData.type === 'user') {
|
||||
recipient = entityData.name;
|
||||
} else {
|
||||
recipient = `/r/${entityData.name}`;
|
||||
}
|
||||
} catch (err: any) {
|
||||
throw new ErrorWithCause(`'to' field for message was not in a valid format, given value after templating: ${renderedTo} -- See ${REDDIT_ENTITY_REGEX_URL} for valid examples`, {cause: err});
|
||||
throw new ErrorWithCause(`'to' field for message was not in a valid format. See ${REDDIT_ENTITY_REGEX_URL} for valid examples`, {cause: err});
|
||||
}
|
||||
if(recipient.includes('/r/') && this.asSubreddit) {
|
||||
throw new SimpleError(`Cannot send a message as a subreddit to another subreddit. Requested recipient: ${recipient}`);
|
||||
@@ -126,7 +123,7 @@ export interface MessageActionConfig extends RequiredRichContent, Footer {
|
||||
asSubreddit: boolean
|
||||
|
||||
/**
|
||||
* Entity to send message to. It can be templated.
|
||||
* Entity to send message to.
|
||||
*
|
||||
* If not present Message be will sent to the Author of the Activity being checked.
|
||||
*
|
||||
@@ -138,9 +135,8 @@ export interface MessageActionConfig extends RequiredRichContent, Footer {
|
||||
*
|
||||
* **Note:** Reddit does not support sending a message AS a subreddit TO another subreddit
|
||||
*
|
||||
* **Tip:** To send a message to the subreddit of the Activity us `to: 'r/{{item.subreddit}}'`
|
||||
*
|
||||
* @examples ["aUserName","u/aUserName","r/aSubreddit", "r/{{item.subreddit}}"]
|
||||
* @pattern ^\s*(\/[ru]\/|[ru]\/)*(\w+)*\s*$
|
||||
* @examples ["aUserName","u/aUserName","r/aSubreddit"]
|
||||
* */
|
||||
to?: string
|
||||
|
||||
|
||||
@@ -1,32 +1,29 @@
|
||||
import {ActionJson, ActionConfig, ActionOptions} from "./index";
|
||||
import Action from "./index";
|
||||
import {Comment} from "snoowrap";
|
||||
import {renderContent} from "../Utils/SnoowrapUtils";
|
||||
import Submission from "snoowrap/dist/objects/Submission";
|
||||
import {ActionProcessResult, RichContent} from "../Common/interfaces";
|
||||
import {buildFilterCriteriaSummary, normalizeModActionCriteria, toModNoteLabel} from "../util";
|
||||
import {toModNoteLabel} from "../util";
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {
|
||||
ActionTypes,
|
||||
ModUserNoteLabel,
|
||||
} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
import {ModNoteCriteria} from "../Common/Infrastructure/Filters/FilterCriteria";
|
||||
import {ActionTypes, ModUserNoteLabel} from "../Common/Infrastructure/Atomic";
|
||||
import {ModNote} from "../Subreddit/ModNotes/ModNote";
|
||||
|
||||
|
||||
export class ModNoteAction extends Action {
|
||||
content: string;
|
||||
type?: string;
|
||||
existingNoteCheck?: ModNoteCriteria
|
||||
allowDuplicate: boolean;
|
||||
referenceActivity: boolean
|
||||
|
||||
constructor(options: ModNoteActionOptions) {
|
||||
super(options);
|
||||
const {type, content = '', existingNoteCheck = true, referenceActivity = true} = options;
|
||||
const {type, content = '', allowDuplicate = false, referenceActivity = true} = options;
|
||||
this.type = type;
|
||||
this.content = content;
|
||||
this.allowDuplicate = allowDuplicate;
|
||||
this.referenceActivity = referenceActivity;
|
||||
this.existingNoteCheck = typeof existingNoteCheck === 'boolean' ? this.generateModLogCriteriaFromDuplicateConvenience(existingNoteCheck) : normalizeModActionCriteria(existingNoteCheck);
|
||||
}
|
||||
|
||||
getKind(): ActionTypes {
|
||||
@@ -37,43 +34,41 @@ export class ModNoteAction extends Action {
|
||||
return {
|
||||
content: this.content,
|
||||
type: this.type,
|
||||
existingNoteCheck: this.existingNoteCheck,
|
||||
allowDuplicate: this.allowDuplicate,
|
||||
referenceActivity: this.referenceActivity,
|
||||
}
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
|
||||
const modLabel = this.type !== undefined ? toModNoteLabel(this.type) : undefined;
|
||||
|
||||
const renderedContent = await this.renderContent(this.content, item, ruleResults, actionResults);
|
||||
const content = await this.resources.getContent(this.content, item.subreddit);
|
||||
const renderedContent = await renderContent(content, item, ruleResults, this.resources.userNotes);
|
||||
this.logger.verbose(`Note:\r\n(${this.type}) ${renderedContent}`);
|
||||
|
||||
let noteCheckPassed: boolean = true;
|
||||
let noteCheckResult: undefined | string;
|
||||
|
||||
if(this.existingNoteCheck === undefined) {
|
||||
// nothing to do!
|
||||
noteCheckResult = 'existingNoteCheck=false so no existing note checks were performed.';
|
||||
} else {
|
||||
const noteCheckCriteriaResult = await this.resources.isAuthor(item, {
|
||||
modActions: [this.existingNoteCheck]
|
||||
});
|
||||
noteCheckPassed = noteCheckCriteriaResult.passed;
|
||||
const {details} = buildFilterCriteriaSummary(noteCheckCriteriaResult);
|
||||
noteCheckResult = `${noteCheckPassed ? 'Existing note check condition succeeded' : 'Will not add note because existing note check condition failed'} -- ${details.join(' ')}`;
|
||||
}
|
||||
|
||||
this.logger.info(noteCheckResult);
|
||||
if (!noteCheckPassed) {
|
||||
return {
|
||||
dryRun,
|
||||
success: false,
|
||||
result: noteCheckResult
|
||||
};
|
||||
}
|
||||
|
||||
// TODO see what changes are made for bulk fetch of notes before implementing this
|
||||
// https://www.reddit.com/r/redditdev/comments/t8w861/new_mod_notes_api/
|
||||
// if (!this.allowDuplicate) {
|
||||
// const notes = await this.resources.userNotes.getUserNotes(item.author);
|
||||
// let existingNote = notes.find((x) => x.link !== null && x.link.includes(item.id));
|
||||
// if(existingNote === undefined && notes.length > 0) {
|
||||
// const lastNote = notes[notes.length - 1];
|
||||
// // possibly notes don't have a reference link so check if last one has same text
|
||||
// if(lastNote.link === null && lastNote.text === renderedContent) {
|
||||
// existingNote = lastNote;
|
||||
// }
|
||||
// }
|
||||
// if (existingNote !== undefined && existingNote.noteType === this.type) {
|
||||
// this.logger.info(`Will not add note because one already exists for this Activity (${existingNote.time.local().format()}) and allowDuplicate=false`);
|
||||
// return {
|
||||
// dryRun,
|
||||
// success: false,
|
||||
// result: `Will not add note because one already exists for this Activity (${existingNote.time.local().format()}) and allowDuplicate=false`
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
if (!dryRun) {
|
||||
await this.resources.addModNote({
|
||||
label: modLabel,
|
||||
@@ -89,36 +84,15 @@ export class ModNoteAction extends Action {
|
||||
result: `${modLabel !== undefined ? `(${modLabel})` : ''} ${renderedContent}`
|
||||
}
|
||||
}
|
||||
|
||||
generateModLogCriteriaFromDuplicateConvenience(val: boolean): ModNoteCriteria | undefined {
|
||||
if(val) {
|
||||
return {
|
||||
noteType: this.type !== undefined ? [toModNoteLabel(this.type)] : undefined,
|
||||
note: this.content !== '' ? [this.content] : undefined,
|
||||
referencesCurrentActivity: this.referenceActivity ? true : undefined,
|
||||
search: 'current',
|
||||
count: '< 1'
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ModNoteActionConfig extends ActionConfig, RichContent {
|
||||
/**
|
||||
* Check if there is an existing Note matching some criteria before adding the Note.
|
||||
*
|
||||
* If this check passes then the Note is added. The value may be a boolean or ModNoteCriteria.
|
||||
*
|
||||
* Boolean convenience:
|
||||
*
|
||||
* * If `true` or undefined then CM generates a ModNoteCriteria that passes only if there is NO existing note matching note criteria
|
||||
* * If `false` then no check is performed and Note is always added
|
||||
*
|
||||
* @examples [true]
|
||||
* @default true
|
||||
* Add Note even if a Note already exists for this Activity
|
||||
* @examples [false]
|
||||
* @default false
|
||||
* */
|
||||
existingNoteCheck?: boolean | ModNoteCriteria,
|
||||
allowDuplicate?: boolean,
|
||||
type?: ModUserNoteLabel
|
||||
referenceActivity?: boolean
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import {isSubmission, truncateStringToLength} from "../util";
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
const truncate = truncateStringToLength(100);
|
||||
export class RemoveAction extends Action {
|
||||
@@ -32,7 +31,7 @@ export class RemoveAction extends Action {
|
||||
this.reasonId = reasonId;
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
const touchedEntities = [];
|
||||
let removeSummary = [];
|
||||
@@ -45,7 +44,7 @@ export class RemoveAction extends Action {
|
||||
removeSummary.push('Marked as SPAM');
|
||||
this.logger.verbose('Marking as spam on removal');
|
||||
}
|
||||
const renderedNote = await this.renderContent(this.note, item, ruleResults, actionResults);
|
||||
const renderedNote = this.note === undefined ? undefined : await this.resources.renderContent(this.note, item, ruleResults);
|
||||
let foundReasonId: string | undefined;
|
||||
let foundReason: string | undefined;
|
||||
|
||||
@@ -100,8 +99,7 @@ export class RemoveAction extends Action {
|
||||
return {
|
||||
dryRun,
|
||||
success: true,
|
||||
touchedEntities,
|
||||
result: removeSummary.join(' | ')
|
||||
touchedEntities
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import {ActionProcessResult, RichContent, RuleResult} from "../Common/interfaces
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
// https://www.reddit.com/dev/api/oauth#POST_api_report
|
||||
// denotes 100 characters maximum
|
||||
@@ -26,9 +25,10 @@ export class ReportAction extends Action {
|
||||
return 'report';
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
const renderedContent = (await this.renderContent(this.content, item, ruleResults, actionResults) as string);
|
||||
const content = await this.resources.getContent(this.content, item.subreddit);
|
||||
const renderedContent = await renderContent(content, item, ruleResults, this.resources.userNotes);
|
||||
this.logger.verbose(`Contents:\r\n${renderedContent}`);
|
||||
const truncatedContent = reportTrunc(renderedContent);
|
||||
const touchedEntities = [];
|
||||
|
||||
@@ -10,7 +10,6 @@ import {ActionTarget, ActionTypes, ArbitraryActionTarget} from "../Common/Infras
|
||||
import {CMError} from "../Utils/Errors";
|
||||
import {SnoowrapActivity} from "../Common/Infrastructure/Reddit";
|
||||
import Subreddit from "snoowrap/dist/objects/Subreddit";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class SubmissionAction extends Action {
|
||||
content?: string;
|
||||
@@ -68,21 +67,21 @@ export class SubmissionAction extends Action {
|
||||
return 'submission';
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
|
||||
const title = await this.renderContent(this.title, item, ruleResults, actionResults) as string;
|
||||
const title = await this.resources.renderContent(this.title, item, ruleResults);
|
||||
this.logger.verbose(`Title: ${title}`);
|
||||
|
||||
const url = await this.renderContent(this.url, item, ruleResults, actionResults);
|
||||
const url = this.url !== undefined ? await this.resources.renderContent(this.url, item, ruleResults) : undefined;
|
||||
|
||||
this.logger.verbose(`URL: ${url !== undefined ? url : '[No URL]'}`);
|
||||
|
||||
const body = await this.renderContent(this.content, item, ruleResults, actionResults);
|
||||
const body = this.content !== undefined ? await this.resources.renderContent(this.content, item, ruleResults) : undefined;
|
||||
|
||||
let renderedContent: string | undefined = undefined;
|
||||
if(body !== undefined) {
|
||||
const footer = await this.resources.renderFooter(item, this.footer);
|
||||
const footer = await this.resources.generateFooter(item, this.footer);
|
||||
renderedContent = `${body}${footer}`;
|
||||
this.logger.verbose(`Contents:\r\n${renderedContent.length > 100 ? `\r\n${renderedContent}` : renderedContent}`);
|
||||
} else {
|
||||
@@ -205,11 +204,6 @@ export class SubmissionAction extends Action {
|
||||
success: !allErrors,
|
||||
result: `${targetResults.join('\n')}${this.url !== undefined ? `\nURL: ${this.url}` : ''}${body !== undefined ? truncateStringToLength(100)(body) : ''}`,
|
||||
touchedEntities,
|
||||
data: {
|
||||
body,
|
||||
bodyShort: body !== undefined ? truncateStringToLength(100)(body) : '',
|
||||
submissions: targetResults.map(x => `* ${x}`).join('\n')
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -315,7 +309,7 @@ export interface SubmissionActionConfig extends RichContent, Footer {
|
||||
* * 'self' -- DEFAULT. Post Submission to same subreddit of Activity being processed
|
||||
* * [subreddit] -- The name of a subreddit to post Submission to. EX mealtimevideos
|
||||
* */
|
||||
targets?: ('self' | string) | ('self' | string)[]
|
||||
targets?: 'self' | string
|
||||
}
|
||||
|
||||
export interface SubmissionActionOptions extends SubmissionActionConfig, ActionOptions {
|
||||
|
||||
@@ -6,7 +6,6 @@ import Comment from 'snoowrap/dist/objects/Comment';
|
||||
import {RuleResultEntity} from "../../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../../Subreddit/Manager";
|
||||
import {ActionTypes} from "../../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class FlairAction extends Action {
|
||||
text: string;
|
||||
@@ -27,7 +26,7 @@ export class FlairAction extends Action {
|
||||
return 'flair';
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
let flairParts = [];
|
||||
if(this.text !== '') {
|
||||
|
||||
@@ -4,7 +4,6 @@ import {ActionProcessResult, RuleResult} from '../Common/interfaces';
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
|
||||
export class UserFlairAction extends Action {
|
||||
text?: string;
|
||||
@@ -23,7 +22,7 @@ export class UserFlairAction extends Action {
|
||||
return 'userflair';
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
let flairParts = [];
|
||||
|
||||
|
||||
@@ -1,76 +1,57 @@
|
||||
import {ActionJson, ActionConfig, ActionOptions} from "./index";
|
||||
import Action from "./index";
|
||||
import {Comment} from "snoowrap";
|
||||
import {renderContent} from "../Utils/SnoowrapUtils";
|
||||
import {UserNoteJson} from "../Subreddit/UserNotes";
|
||||
import Submission from "snoowrap/dist/objects/Submission";
|
||||
import {ActionProcessResult, RuleResult} from "../Common/interfaces";
|
||||
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
|
||||
import {runCheckOptions} from "../Subreddit/Manager";
|
||||
import {ActionTypes, UserNoteType} from "../Common/Infrastructure/Atomic";
|
||||
import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
import {
|
||||
FullUserNoteCriteria,
|
||||
toFullUserNoteCriteria, UserNoteCriteria
|
||||
} from "../Common/Infrastructure/Filters/FilterCriteria";
|
||||
import {buildFilterCriteriaSummary} from "../util";
|
||||
|
||||
|
||||
export class UserNoteAction extends Action {
|
||||
content: string;
|
||||
type: UserNoteType;
|
||||
existingNoteCheck?: UserNoteCriteria
|
||||
allowDuplicate: boolean;
|
||||
|
||||
constructor(options: UserNoteActionOptions) {
|
||||
super(options);
|
||||
const {type, content = '', existingNoteCheck = true, allowDuplicate} = options;
|
||||
const {type, content = '', allowDuplicate = false} = options;
|
||||
this.type = type;
|
||||
this.content = content;
|
||||
if(typeof existingNoteCheck !== 'boolean') {
|
||||
this.existingNoteCheck = existingNoteCheck;
|
||||
} else {
|
||||
let exNotecheck: boolean;
|
||||
if(allowDuplicate !== undefined) {
|
||||
exNotecheck = !allowDuplicate;
|
||||
} else {
|
||||
exNotecheck = existingNoteCheck;
|
||||
}
|
||||
this.existingNoteCheck = this.generateCriteriaFromDuplicateConvenience(exNotecheck);
|
||||
}
|
||||
this.allowDuplicate = allowDuplicate;
|
||||
}
|
||||
|
||||
getKind(): ActionTypes {
|
||||
return 'usernote';
|
||||
}
|
||||
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
async process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult> {
|
||||
const dryRun = this.getRuntimeAwareDryrun(options);
|
||||
const renderedContent = (await this.renderContent(this.content, item, ruleResults, actionResults) as string);
|
||||
const content = await this.resources.getContent(this.content, item.subreddit);
|
||||
const renderedContent = await renderContent(content, item, ruleResults, this.resources.userNotes);
|
||||
this.logger.verbose(`Note:\r\n(${this.type}) ${renderedContent}`);
|
||||
|
||||
let noteCheckPassed: boolean = true;
|
||||
let noteCheckResult: undefined | string;
|
||||
|
||||
if(this.existingNoteCheck === undefined) {
|
||||
// nothing to do!
|
||||
noteCheckResult = 'existingNoteCheck=false so no existing note checks were performed.';
|
||||
} else {
|
||||
const noteCheckCriteriaResult = await this.resources.isAuthor(item, {
|
||||
userNotes: [this.existingNoteCheck]
|
||||
});
|
||||
noteCheckPassed = noteCheckCriteriaResult.passed;
|
||||
const {details} = buildFilterCriteriaSummary(noteCheckCriteriaResult);
|
||||
noteCheckResult = `${noteCheckPassed ? 'Existing note check condition succeeded' : 'Will not add note because existing note check condition failed'} -- ${details.join(' ')}`;
|
||||
if (!this.allowDuplicate) {
|
||||
const notes = await this.resources.userNotes.getUserNotes(item.author);
|
||||
let existingNote = notes.find((x) => x.link !== null && x.link.includes(item.id));
|
||||
if(existingNote === undefined && notes.length > 0) {
|
||||
const lastNote = notes[notes.length - 1];
|
||||
// possibly notes don't have a reference link so check if last one has same text
|
||||
if(lastNote.link === null && lastNote.text === renderedContent) {
|
||||
existingNote = lastNote;
|
||||
}
|
||||
}
|
||||
if (existingNote !== undefined && existingNote.noteType === this.type) {
|
||||
this.logger.info(`Will not add note because one already exists for this Activity (${existingNote.time.local().format()}) and allowDuplicate=false`);
|
||||
return {
|
||||
dryRun,
|
||||
success: false,
|
||||
result: `Will not add note because one already exists for this Activity (${existingNote.time.local().format()}) and allowDuplicate=false`
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.info(noteCheckResult);
|
||||
if (!noteCheckPassed) {
|
||||
return {
|
||||
dryRun,
|
||||
success: false,
|
||||
result: noteCheckResult
|
||||
};
|
||||
}
|
||||
|
||||
if (!dryRun) {
|
||||
await this.resources.userNotes.addUserNote(item, this.type, renderedContent, this.name !== undefined ? `(Action ${this.name})` : '');
|
||||
} else if (!await this.resources.userNotes.warningExists(this.type)) {
|
||||
@@ -83,23 +64,11 @@ export class UserNoteAction extends Action {
|
||||
}
|
||||
}
|
||||
|
||||
generateCriteriaFromDuplicateConvenience(val: boolean): UserNoteCriteria | undefined {
|
||||
if(val) {
|
||||
return {
|
||||
type: this.type,
|
||||
note: this.content !== '' && this.content !== undefined && this.content !== null ? [this.content] : undefined,
|
||||
search: 'current',
|
||||
count: '< 1'
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
protected getSpecificPremise(): object {
|
||||
return {
|
||||
content: this.content,
|
||||
type: this.type,
|
||||
existingNoteCheck: this.existingNoteCheck
|
||||
allowDuplicate: this.allowDuplicate
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,29 +76,10 @@ export class UserNoteAction extends Action {
|
||||
export interface UserNoteActionConfig extends ActionConfig,UserNoteJson {
|
||||
/**
|
||||
* Add Note even if a Note already exists for this Activity
|
||||
*
|
||||
* USE `existingNoteCheck` INSTEAD
|
||||
*
|
||||
* @examples [false]
|
||||
* @default false
|
||||
* @deprecated
|
||||
* */
|
||||
allowDuplicate?: boolean,
|
||||
|
||||
/**
|
||||
* Check if there is an existing Note matching some criteria before adding the Note.
|
||||
*
|
||||
* If this check passes then the Note is added. The value may be a boolean or UserNoteCriteria.
|
||||
*
|
||||
* Boolean convenience:
|
||||
*
|
||||
* * If `true` or undefined then CM generates a UserNoteCriteria that passes only if there is NO existing note matching note criteria
|
||||
* * If `false` then no check is performed and Note is always added
|
||||
*
|
||||
* @examples [true]
|
||||
* @default true
|
||||
* */
|
||||
existingNoteCheck?: boolean | UserNoteCriteria,
|
||||
}
|
||||
|
||||
export interface UserNoteActionOptions extends Omit<UserNoteActionConfig, 'authorIs' | 'itemIs'>, ActionOptions {
|
||||
|
||||
@@ -19,8 +19,6 @@ import {ActionResultEntity} from "../Common/Entities/ActionResultEntity";
|
||||
import {FindOptionsWhere} from "typeorm/find-options/FindOptionsWhere";
|
||||
import {ActionTypes} from "../Common/Infrastructure/Atomic";
|
||||
import {RunnableBaseJson, RunnableBaseOptions, StructuredRunnableBase} from "../Common/Infrastructure/Runnable";
|
||||
import { SubredditResources } from "../Subreddit/SubredditResources";
|
||||
import {SnoowrapActivity} from "../Common/Infrastructure/Reddit";
|
||||
|
||||
export abstract class Action extends RunnableBase {
|
||||
name?: string;
|
||||
@@ -31,8 +29,6 @@ export abstract class Action extends RunnableBase {
|
||||
managerEmitter: EventEmitter;
|
||||
// actionEntity: ActionEntity | null = null;
|
||||
actionPremiseEntity: ActionPremise | null = null;
|
||||
checkName: string;
|
||||
subredditName: string;
|
||||
|
||||
constructor(options: ActionOptions) {
|
||||
super(options);
|
||||
@@ -44,7 +40,6 @@ export abstract class Action extends RunnableBase {
|
||||
subredditName,
|
||||
dryRun = false,
|
||||
emitter,
|
||||
checkName,
|
||||
} = options;
|
||||
|
||||
this.name = name;
|
||||
@@ -53,8 +48,6 @@ export abstract class Action extends RunnableBase {
|
||||
this.client = client;
|
||||
this.logger = logger.child({labels: [`Action ${this.getActionUniqueName()}`]}, mergeArr);
|
||||
this.managerEmitter = emitter;
|
||||
this.checkName = checkName;
|
||||
this.subredditName = subredditName;
|
||||
}
|
||||
|
||||
abstract getKind(): ActionTypes;
|
||||
@@ -119,7 +112,7 @@ export abstract class Action extends RunnableBase {
|
||||
}
|
||||
}
|
||||
|
||||
async handle(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionResultEntity> {
|
||||
async handle(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionResultEntity> {
|
||||
const {dryRun: runtimeDryrun} = options;
|
||||
const dryRun = runtimeDryrun || this.dryRun;
|
||||
|
||||
@@ -155,11 +148,10 @@ export abstract class Action extends RunnableBase {
|
||||
actRes.runReason = runReason;
|
||||
return actRes;
|
||||
}
|
||||
const results = await this.process(item, ruleResults, actionResults, options);
|
||||
const results = await this.process(item, ruleResults, options);
|
||||
actRes.success = results.success;
|
||||
actRes.dryRun = results.dryRun;
|
||||
actRes.result = results.result;
|
||||
actRes.data = results.data;
|
||||
actRes.touchedEntities = results.touchedEntities ?? [];
|
||||
|
||||
return actRes;
|
||||
@@ -174,31 +166,20 @@ export abstract class Action extends RunnableBase {
|
||||
}
|
||||
}
|
||||
|
||||
abstract process(item: Comment | Submission, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[], options: runCheckOptions): Promise<ActionProcessResult>;
|
||||
abstract process(item: Comment | Submission, ruleResults: RuleResultEntity[], options: runCheckOptions): Promise<ActionProcessResult>;
|
||||
|
||||
getRuntimeAwareDryrun(options: runCheckOptions): boolean {
|
||||
const {dryRun: runtimeDryrun} = options;
|
||||
return runtimeDryrun || this.dryRun;
|
||||
}
|
||||
|
||||
async renderContent(template: string | undefined, item: SnoowrapActivity, ruleResults: RuleResultEntity[], actionResults: ActionResultEntity[]): Promise<string | undefined> {
|
||||
if(template === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return await this.resources.renderContent(template, item, ruleResults, actionResults, {manager: this.subredditName, check: this.checkName});
|
||||
}
|
||||
}
|
||||
|
||||
export interface ActionRuntimeOptions {
|
||||
checkName: string
|
||||
subredditName: string
|
||||
export interface ActionOptions extends Omit<ActionConfig, 'authorIs' | 'itemIs'>, RunnableBaseOptions {
|
||||
//logger: Logger;
|
||||
subredditName: string;
|
||||
//resources: SubredditResources;
|
||||
client: ExtendedSnoowrap;
|
||||
emitter: EventEmitter;
|
||||
resources: SubredditResources;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
export interface ActionOptions extends Omit<ActionConfig, 'authorIs' | 'itemIs'>, RunnableBaseOptions, ActionRuntimeOptions {
|
||||
emitter: EventEmitter
|
||||
}
|
||||
|
||||
export interface ActionConfig extends RunnableBaseJson {
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
import {SPoll} from "../Subreddit/Streams";
|
||||
import Snoowrap from "snoowrap";
|
||||
import {Cache} from "cache-manager";
|
||||
import {
|
||||
BotInstanceConfig,
|
||||
StrongCache,
|
||||
StrongTTLConfig,
|
||||
ThirdPartyCredentialsJsonConfig,
|
||||
TTLConfig
|
||||
} from "../Common/interfaces";
|
||||
import winston, {Logger} from "winston";
|
||||
import {DataSource, Repository} from "typeorm";
|
||||
import {
|
||||
EventRetentionPolicyRange
|
||||
} from "../Common/Infrastructure/Atomic";
|
||||
import {InvokeeType} from "../Common/Entities/InvokeeType";
|
||||
import {RunStateType} from "../Common/Entities/RunStateType";
|
||||
import {buildCachePrefix, cacheStats, mergeArr, toStrongTTLConfig} from "../util";
|
||||
import objectHash from "object-hash";
|
||||
import {runMigrations} from "../Common/Migrations/CacheMigrationUtils";
|
||||
import {CMError} from "../Utils/Errors";
|
||||
import {DEFAULT_FOOTER, SubredditResources} from "../Subreddit/SubredditResources";
|
||||
import {SubredditResourceConfig, SubredditResourceOptions} from "../Common/Subreddit/SubredditResourceInterfaces";
|
||||
import {buildCacheOptionsFromProvider, CMCache, createCacheManager} from "../Common/Cache";
|
||||
|
||||
export class BotResourcesManager {
|
||||
resources: Map<string, SubredditResources> = new Map();
|
||||
authorTTL: number = 10000;
|
||||
enabled: boolean = true;
|
||||
modStreams: Map<string, SPoll<Snoowrap.Submission | Snoowrap.Comment>> = new Map();
|
||||
defaultCache: CMCache;
|
||||
defaultCacheConfig: StrongCache
|
||||
defaultCacheMigrated: boolean = false;
|
||||
cacheType: string = 'none';
|
||||
cacheHash: string;
|
||||
ttlDefaults: StrongTTLConfig
|
||||
defaultThirdPartyCredentials: ThirdPartyCredentialsJsonConfig;
|
||||
logger: Logger;
|
||||
botAccount?: string;
|
||||
defaultDatabase: DataSource
|
||||
botName!: string
|
||||
retention?: EventRetentionPolicyRange
|
||||
|
||||
invokeeRepo: Repository<InvokeeType>
|
||||
runTypeRepo: Repository<RunStateType>
|
||||
|
||||
constructor(config: BotInstanceConfig, logger: Logger) {
|
||||
const {
|
||||
caching: {
|
||||
authorTTL,
|
||||
userNotesTTL,
|
||||
wikiTTL,
|
||||
commentTTL,
|
||||
submissionTTL,
|
||||
subredditTTL,
|
||||
filterCriteriaTTL,
|
||||
modNotesTTL,
|
||||
selfTTL,
|
||||
provider,
|
||||
},
|
||||
name,
|
||||
credentials: {
|
||||
reddit,
|
||||
...thirdParty
|
||||
},
|
||||
database,
|
||||
databaseConfig: {
|
||||
retention
|
||||
} = {},
|
||||
caching,
|
||||
} = config;
|
||||
caching.provider.prefix = buildCachePrefix([caching.provider.prefix, 'SHARED']);
|
||||
const {...relevantCacheSettings} = caching;
|
||||
this.cacheHash = objectHash.sha1(relevantCacheSettings);
|
||||
this.defaultCacheConfig = caching;
|
||||
this.defaultThirdPartyCredentials = thirdParty;
|
||||
this.defaultDatabase = database;
|
||||
this.ttlDefaults = toStrongTTLConfig({
|
||||
authorTTL,
|
||||
userNotesTTL,
|
||||
wikiTTL,
|
||||
commentTTL,
|
||||
submissionTTL,
|
||||
filterCriteriaTTL,
|
||||
subredditTTL,
|
||||
selfTTL,
|
||||
modNotesTTL
|
||||
});
|
||||
this.botName = name as string;
|
||||
this.logger = logger;
|
||||
this.invokeeRepo = this.defaultDatabase.getRepository(InvokeeType);
|
||||
this.runTypeRepo = this.defaultDatabase.getRepository(RunStateType);
|
||||
this.retention = retention;
|
||||
|
||||
const options = provider;
|
||||
this.cacheType = options.store;
|
||||
|
||||
const cache = createCacheManager(options);
|
||||
this.defaultCache = new CMCache(cache, options, true, caching.provider.prefix, this.ttlDefaults, this.logger);
|
||||
}
|
||||
|
||||
get(subName: string): SubredditResources | undefined {
|
||||
if (this.resources.has(subName)) {
|
||||
return this.resources.get(subName) as SubredditResources;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async set(subName: string, initOptions: SubredditResourceConfig): Promise<SubredditResources> {
|
||||
let hash = 'default';
|
||||
const {caching, credentials, retention, ...init} = initOptions;
|
||||
|
||||
const res = this.get(subName);
|
||||
|
||||
let opts: SubredditResourceOptions = {
|
||||
cache: this.defaultCache,
|
||||
cacheType: this.cacheType,
|
||||
cacheSettingsHash: hash,
|
||||
ttl: this.ttlDefaults,
|
||||
thirdPartyCredentials: credentials ?? this.defaultThirdPartyCredentials,
|
||||
prefix: this.defaultCacheConfig.provider.prefix,
|
||||
database: this.defaultDatabase,
|
||||
botName: this.botName,
|
||||
retention: retention ?? this.retention,
|
||||
...init,
|
||||
};
|
||||
|
||||
if (caching !== undefined) {
|
||||
const {
|
||||
provider = this.defaultCacheConfig.provider,
|
||||
...rest
|
||||
} = caching;
|
||||
|
||||
opts.ttl = toStrongTTLConfig({
|
||||
...this.ttlDefaults,
|
||||
...rest
|
||||
});
|
||||
|
||||
const candidateProvider = buildCacheOptionsFromProvider(provider);
|
||||
|
||||
const defaultPrefix = candidateProvider.prefix;
|
||||
const subPrefix = defaultPrefix === this.defaultCacheConfig.provider.prefix ? buildCachePrefix([(defaultPrefix !== undefined ? defaultPrefix.replace('SHARED', '') : defaultPrefix), subName]) : candidateProvider.prefix;
|
||||
candidateProvider.prefix = subPrefix;
|
||||
|
||||
if(this.defaultCache.equalProvider(candidateProvider)) {
|
||||
opts.cache = this.defaultCache;
|
||||
} else if(res !== undefined && res.cache.equalProvider(candidateProvider)) {
|
||||
opts.cache = res.cache;
|
||||
} else {
|
||||
opts.cache = new CMCache(createCacheManager(candidateProvider), candidateProvider, false, this.defaultCache.providerOptions.prefix, opts.ttl, this.logger);
|
||||
await runMigrations(opts.cache.cache, opts.cache.logger, candidateProvider.prefix);
|
||||
}
|
||||
|
||||
} else if (!this.defaultCacheMigrated) {
|
||||
await runMigrations(this.defaultCache.cache, this.logger, opts.prefix);
|
||||
this.defaultCacheMigrated = true;
|
||||
}
|
||||
|
||||
let resource: SubredditResources;
|
||||
if (res === undefined) {
|
||||
resource = new SubredditResources(subName, {
|
||||
...opts,
|
||||
botAccount: this.botAccount
|
||||
});
|
||||
this.resources.set(subName, resource);
|
||||
} else {
|
||||
// just set non-cache related settings
|
||||
resource = res;
|
||||
resource.botAccount = this.botAccount;
|
||||
}
|
||||
await resource.configure(opts);
|
||||
|
||||
return resource;
|
||||
}
|
||||
|
||||
async destroy(subName: string) {
|
||||
const res = this.get(subName);
|
||||
if (res !== undefined) {
|
||||
await res.destroy();
|
||||
this.resources.delete(subName);
|
||||
}
|
||||
}
|
||||
|
||||
async getPendingSubredditInvites(): Promise<(string[])> {
|
||||
const subredditNames = await this.defaultCache.get(`modInvites`);
|
||||
if (subredditNames !== undefined && subredditNames !== null) {
|
||||
return subredditNames as string[];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
async addPendingSubredditInvite(subreddit: string): Promise<void> {
|
||||
if (subreddit === null || subreddit === undefined || subreddit == '') {
|
||||
throw new CMError('Subreddit name cannot be empty');
|
||||
}
|
||||
let subredditNames = await this.defaultCache.get(`modInvites`) as (string[] | undefined | null);
|
||||
if (subredditNames === undefined || subredditNames === null) {
|
||||
subredditNames = [];
|
||||
}
|
||||
const cleanName = subreddit.trim();
|
||||
|
||||
if (subredditNames.some(x => x.trim().toLowerCase() === cleanName.toLowerCase())) {
|
||||
throw new CMError(`An invite for the Subreddit '${subreddit}' already exists`);
|
||||
}
|
||||
subredditNames.push(cleanName);
|
||||
await this.defaultCache.set(`modInvites`, subredditNames, {ttl: 0});
|
||||
return;
|
||||
}
|
||||
|
||||
async deletePendingSubredditInvite(subreddit: string): Promise<void> {
|
||||
let subredditNames = await this.defaultCache.get(`modInvites`) as (string[] | undefined | null);
|
||||
if (subredditNames === undefined || subredditNames === null) {
|
||||
subredditNames = [];
|
||||
}
|
||||
subredditNames = subredditNames.filter(x => x.toLowerCase() !== subreddit.trim().toLowerCase());
|
||||
await this.defaultCache.set(`modInvites`, subredditNames, {ttl: 0});
|
||||
return;
|
||||
}
|
||||
|
||||
async clearPendingSubredditInvites(): Promise<void> {
|
||||
await this.defaultCache.del(`modInvites`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
250
src/Bot/index.ts
@@ -1,5 +1,4 @@
|
||||
import Snoowrap, {Comment, ConfigOptions, RedditUser, Submission} from "snoowrap";
|
||||
import {Subreddit} from "snoowrap/dist/objects"
|
||||
import Snoowrap, {Comment, ConfigOptions, RedditUser, Submission, Subreddit} from "snoowrap";
|
||||
import {Logger} from "winston";
|
||||
import dayjs, {Dayjs} from "dayjs";
|
||||
import {Duration} from "dayjs/plugin/duration";
|
||||
@@ -25,17 +24,10 @@ import {
|
||||
import {Manager} from "../Subreddit/Manager";
|
||||
import {ExtendedSnoowrap, ProxiedSnoowrap} from "../Utils/SnoowrapClients";
|
||||
import {CommentStream, ModQueueStream, SPoll, SubmissionStream, UnmoderatedStream} from "../Subreddit/Streams";
|
||||
import {BotResourcesManager} from "../Subreddit/SubredditResources";
|
||||
import LoggedError from "../Utils/LoggedError";
|
||||
import pEvent from "p-event";
|
||||
import {
|
||||
SimpleError,
|
||||
isRateLimitError,
|
||||
isRequestError,
|
||||
isScopeError,
|
||||
isStatusError,
|
||||
CMError,
|
||||
ISeriousError, definesSeriousError
|
||||
} from "../Utils/Errors";
|
||||
import {SimpleError, isRateLimitError, isRequestError, isScopeError, isStatusError, CMError} from "../Utils/Errors";
|
||||
import {ErrorWithCause} from "pony-cause";
|
||||
import {DataSource, Repository} from "typeorm";
|
||||
import {Bot as BotEntity} from '../Common/Entities/Bot';
|
||||
@@ -51,18 +43,10 @@ import {FilterCriteriaDefaults} from "../Common/Infrastructure/Filters/FilterSha
|
||||
import {snooLogWrapper} from "../Utils/loggerFactory";
|
||||
import {InfluxClient} from "../Common/Influx/InfluxClient";
|
||||
import {Point} from "@influxdata/influxdb-client";
|
||||
import {
|
||||
BotInstanceFunctions, HydratedSubredditInviteData,
|
||||
NormalizedManagerResponse,
|
||||
SubredditInviteData,
|
||||
SubredditInviteDataPersisted, SubredditOnboardingReadiness
|
||||
} from "../Web/Common/interfaces";
|
||||
import {BotInstanceFunctions, NormalizedManagerResponse} from "../Web/Common/interfaces";
|
||||
import {AuthorEntity} from "../Common/Entities/AuthorEntity";
|
||||
import {Guest, GuestEntityData} from "../Common/Entities/Guest/GuestInterfaces";
|
||||
import {guestEntitiesToAll, guestEntityToApiGuest} from "../Common/Entities/Guest/GuestEntity";
|
||||
import {SubredditInvite} from "../Common/Entities/SubredditInvite";
|
||||
import {dayjsDTFormat} from "../Common/defaults";
|
||||
import {BotResourcesManager} from "./ResourcesManager";
|
||||
|
||||
class Bot implements BotInstanceFunctions {
|
||||
|
||||
@@ -77,7 +61,6 @@ class Bot implements BotInstanceFunctions {
|
||||
excludeSubreddits: string[];
|
||||
filterCriteriaDefaults?: FilterCriteriaDefaults
|
||||
subManagers: Manager[] = [];
|
||||
moderatedSubreddits: Subreddit[] = []
|
||||
heartbeatInterval: number;
|
||||
nextHeartbeat: Dayjs = dayjs();
|
||||
heartBeating: boolean = false;
|
||||
@@ -122,8 +105,6 @@ class Bot implements BotInstanceFunctions {
|
||||
runTypeRepo: Repository<RunStateType>;
|
||||
managerRepo: Repository<ManagerEntity>;
|
||||
authorRepo: Repository<AuthorEntity>;
|
||||
subredditInviteRepo: Repository<SubredditInvite>
|
||||
botRepo: Repository<BotEntity>
|
||||
botEntity!: BotEntity
|
||||
|
||||
getBotName = () => {
|
||||
@@ -187,8 +168,6 @@ class Bot implements BotInstanceFunctions {
|
||||
this.runTypeRepo = this.database.getRepository(RunStateType);
|
||||
this.managerRepo = this.database.getRepository(ManagerEntity);
|
||||
this.authorRepo = this.database.getRepository(AuthorEntity);
|
||||
this.subredditInviteRepo = this.database.getRepository(SubredditInvite)
|
||||
this.botRepo = this.database.getRepository(BotEntity)
|
||||
this.config = config;
|
||||
this.dryRun = parseBool(dryRun) === true ? true : undefined;
|
||||
this.softLimit = softLimit;
|
||||
@@ -407,7 +386,7 @@ class Bot implements BotInstanceFunctions {
|
||||
async testClient(initial = true) {
|
||||
try {
|
||||
// @ts-ignore
|
||||
const user = await this.client.getMe().fetch();
|
||||
const user = this.client.getMe().fetch();
|
||||
this.logger.info('Test API call successful');
|
||||
return user;
|
||||
} catch (err: any) {
|
||||
@@ -427,27 +406,18 @@ class Bot implements BotInstanceFunctions {
|
||||
}
|
||||
}
|
||||
|
||||
async getModeratedSubreddits(refresh = false) {
|
||||
|
||||
if(this.moderatedSubreddits.length > 0 && !refresh) {
|
||||
return this.moderatedSubreddits;
|
||||
}
|
||||
|
||||
let subListing = await this.client.getModeratedSubreddits({count: 100});
|
||||
while (!subListing.isFinished) {
|
||||
subListing = await subListing.fetchMore({amount: 100});
|
||||
}
|
||||
const availSubs = subListing.filter(x => x.display_name !== `u_${this.botUser?.name}`);
|
||||
this.moderatedSubreddits = availSubs;
|
||||
return availSubs;
|
||||
}
|
||||
|
||||
async buildManagers(subreddits: string[] = []) {
|
||||
await this.init();
|
||||
|
||||
this.logger.verbose('Syncing subreddits to moderate with managers...');
|
||||
|
||||
const availSubs = await this.getModeratedSubreddits(true);
|
||||
let availSubs: Subreddit[] = [];
|
||||
|
||||
let subListing = await this.client.getModeratedSubreddits({count: 100});
|
||||
while(!subListing.isFinished) {
|
||||
subListing = await subListing.fetchMore({amount: 100});
|
||||
}
|
||||
availSubs = subListing.filter(x => x.display_name !== `u_${this.botUser?.name}`);
|
||||
|
||||
this.logger.verbose(`${this.botAccount} is a moderator of these subreddits: ${availSubs.map(x => x.display_name_prefixed).join(', ')}`);
|
||||
|
||||
@@ -529,7 +499,7 @@ class Bot implements BotInstanceFunctions {
|
||||
for (const sub of subsToRun) {
|
||||
if(!this.subManagers.some(x => x.subreddit.display_name === sub.display_name)) {
|
||||
subManagersChanged = true;
|
||||
this.logger.info(`Manager for ${sub.display_name_prefixed} not found in loaded managers. Loading now...`);
|
||||
this.logger.info(`Manager for ${sub.display_name_prefixed} not found in existing managers. Creating now...`);
|
||||
subsToInit.push(sub.display_name);
|
||||
try {
|
||||
this.subManagers.push(await this.createManager(sub));
|
||||
@@ -665,7 +635,7 @@ class Bot implements BotInstanceFunctions {
|
||||
await manager.parseConfiguration('system', true, {suppressNotification: true, suppressChangeEvent: true});
|
||||
} catch (err: any) {
|
||||
if(err.logged !== true) {
|
||||
const normalizedError = new ErrorWithCause(`Bot could not initialize manager`, {cause: err});
|
||||
const normalizedError = new ErrorWithCause(`Bot could not initialize manager because config was not valid`, {cause: err});
|
||||
// @ts-ignore
|
||||
this.logger.error(normalizedError, {subreddit: manager.subreddit.display_name_prefixed});
|
||||
} else {
|
||||
@@ -743,9 +713,6 @@ class Bot implements BotInstanceFunctions {
|
||||
eventsState: new EventsRunState({invokee, runType}),
|
||||
managerState: new ManagerRunState({invokee, runType})
|
||||
}));
|
||||
this.logger.info(`Created new Manager (${managerEntity.id}) for ${subVal.display_name}`);
|
||||
} else {
|
||||
this.logger.info(`Found existing Manager (${managerEntity.id}) for ${subVal.display_name}`);
|
||||
}
|
||||
|
||||
const manager = new Manager(sub, this.client, this.logger, this.cacheManager, {
|
||||
@@ -793,50 +760,21 @@ class Bot implements BotInstanceFunctions {
|
||||
}
|
||||
|
||||
async checkModInvites() {
|
||||
this.logger.debug('Checking onboarding invites...');
|
||||
const expired = this.botEntity.getSubredditInvites().filter(x => x.expiresAt !== undefined && x.expiresAt.isSameOrBefore(dayjs()));
|
||||
for (const exp of expired) {
|
||||
this.logger.debug(`Onboarding invite for ${exp.subreddit} expired at ${exp.expiresAt?.format(dayjsDTFormat)}`);
|
||||
await this.deleteSubredditInvite(exp);
|
||||
}
|
||||
|
||||
for (const subInvite of this.botEntity.getSubredditInvites()) {
|
||||
if (subInvite.canAutomaticallyAccept()) {
|
||||
try {
|
||||
await this.acceptModInvite(subInvite);
|
||||
await this.deleteSubredditInvite(subInvite);
|
||||
} catch (err: any) {
|
||||
if(definesSeriousError(err) && !err.isSerious) {
|
||||
this.logger.warn(err);
|
||||
} else {
|
||||
this.logger.error(err);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.logger.debug(`Cannot try to automatically accept mod invite for ${subInvite.subreddit} because it has additional settings that require moderator approval`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async acceptModInvite(invite: SubredditInvite) {
|
||||
const {subreddit: name} = invite;
|
||||
try {
|
||||
// @ts-ignore
|
||||
await this.client.getSubreddit(name).acceptModeratorInvite();
|
||||
this.logger.info(`Accepted moderator invite for r/${name}!`);
|
||||
} catch (err: any) {
|
||||
if (err.message.includes('NO_INVITE_FOUND')) {
|
||||
throw new SimpleError(`No pending moderation invite for r/${name} was found`, {isSerious: false});
|
||||
} else if (isStatusError(err) && err.statusCode === 403) {
|
||||
let msg = `Error occurred while checking r/${name} for a pending moderation invite.`;
|
||||
if(!this.client.scope.includes('modself')) {
|
||||
msg = `${msg} This bot must have the 'modself' oauth permission in order to accept invites.`;
|
||||
const subs: string[] = await this.cacheManager.getPendingSubredditInvites();
|
||||
for (const name of subs) {
|
||||
try {
|
||||
// @ts-ignore
|
||||
await this.client.getSubreddit(name).acceptModeratorInvite();
|
||||
this.logger.info(`Accepted moderator invite for r/${name}!`);
|
||||
await this.cacheManager.deletePendingSubredditInvite(name);
|
||||
} catch (err: any) {
|
||||
if (err.message.includes('NO_INVITE_FOUND')) {
|
||||
this.logger.warn(`No pending moderation invite for r/${name} was found`);
|
||||
} else if (isStatusError(err) && err.statusCode === 403) {
|
||||
this.logger.error(`Error occurred while checking r/${name} for a pending moderation invite. It is likely that this bot does not have the 'modself' oauth permission. Error: ${err.message}`);
|
||||
} else {
|
||||
msg = `${msg} If this subreddit is private it is likely no moderation invite exists.`;
|
||||
this.logger.error(`Error occurred while checking r/${name} for a pending moderation invite. Error: ${err.message}`);
|
||||
}
|
||||
throw new CMError(msg, {cause: err})
|
||||
} else {
|
||||
throw new CMError(`Error occurred while checking r/${name} for a pending moderation invite.`, {cause: err});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1298,140 +1236,6 @@ class Bot implements BotInstanceFunctions {
|
||||
|
||||
return newGuests;
|
||||
}
|
||||
|
||||
async addSubredditInvite(data: HydratedSubredditInviteData){
|
||||
let sub: Subreddit;
|
||||
let name: string;
|
||||
if (data.subreddit instanceof Subreddit) {
|
||||
sub = data.subreddit;
|
||||
name = sub.display_name;
|
||||
} else {
|
||||
try {
|
||||
const maybeName = parseRedditEntity(data.subreddit);
|
||||
name = maybeName.name;
|
||||
} catch (e: any) {
|
||||
throw new SimpleError(`Value '${data.subreddit}' is not a valid subreddit name`);
|
||||
}
|
||||
try {
|
||||
const [exists, foundSub] = await this.client.subredditExists(name);
|
||||
if (!exists) {
|
||||
throw new SimpleError(`No subreddit with the name ${name} exists`);
|
||||
}
|
||||
if (foundSub !== undefined) {
|
||||
name = foundSub.display_name;
|
||||
}
|
||||
} catch (e: any) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
if((await this.subredditInviteRepo.findOneBy({subreddit: name}))) {
|
||||
throw new CMError(`Invite for ${name} already exists`);
|
||||
}
|
||||
const invite = new SubredditInvite({
|
||||
subreddit: name,
|
||||
initialConfig: data.initialConfig,
|
||||
guests: data.guests,
|
||||
bot: this.botEntity
|
||||
})
|
||||
await this.subredditInviteRepo.save(invite);
|
||||
this.botEntity.addSubredditInvite(invite);
|
||||
return invite;
|
||||
}
|
||||
|
||||
getSubredditInvites(): SubredditInviteDataPersisted[] {
|
||||
if(this.botEntity !== undefined) {
|
||||
return this.botEntity.getSubredditInvites().map(x => x.toSubredditInviteData());
|
||||
}
|
||||
this.logger.warn('No bot entity found');
|
||||
return [];
|
||||
}
|
||||
|
||||
getInvite(id: string): SubredditInvite | undefined {
|
||||
if(this.botEntity !== undefined) {
|
||||
return this.botEntity.getSubredditInvites().find(x => x.id === id);
|
||||
}
|
||||
this.logger.warn('No bot entity found');
|
||||
return undefined;
|
||||
}
|
||||
|
||||
getOnboardingReadiness(invite: SubredditInvite): SubredditOnboardingReadiness {
|
||||
const hasManager = this.subManagers.some(x => x.subreddit.display_name.toLowerCase() === invite.subreddit.toLowerCase());
|
||||
const isMod = this.moderatedSubreddits.some(x => x.display_name.toLowerCase() === invite.subreddit.toLowerCase());
|
||||
return {
|
||||
hasManager,
|
||||
isMod
|
||||
};
|
||||
}
|
||||
|
||||
async finishOnboarding(invite: SubredditInvite) {
|
||||
const readiness = this.getOnboardingReadiness(invite);
|
||||
if (readiness.hasManager || readiness.isMod) {
|
||||
this.logger.info(`Bot is already a mod of ${invite.subreddit}. Finishing onboarding early.`);
|
||||
await this.deleteSubredditInvite(invite);
|
||||
}
|
||||
try {
|
||||
await this.acceptModInvite(invite);
|
||||
} catch (e: any) {
|
||||
throw e;
|
||||
}
|
||||
try {
|
||||
// rebuild managers to get new subreddit
|
||||
await this.buildManagers();
|
||||
const manager = this.subManagers.find(x => x.subreddit.display_name.toLowerCase() === invite.subreddit.toLowerCase());
|
||||
if (manager === undefined) {
|
||||
throw new CMError('Accepted moderator invitation but could not find manager after rebuilding??');
|
||||
}
|
||||
const {guests = [], initialConfig} = invite;
|
||||
|
||||
// add guests
|
||||
if (guests.length > 0) {
|
||||
await this.addGuest(guests, dayjs().add(1, 'day'), manager.subreddit.display_name);
|
||||
}
|
||||
|
||||
// set initial config
|
||||
if (initialConfig !== undefined) {
|
||||
let data: string;
|
||||
try {
|
||||
const res = await manager.resources.getExternalResource(initialConfig);
|
||||
data = res.val;
|
||||
} catch (e: any) {
|
||||
throw new CMError(`Accepted moderator invitation but error occurred while trying to fetch config from Initial Config value (${initialConfig})`, {cause: e});
|
||||
}
|
||||
try {
|
||||
await manager.writeConfig(data, 'Generated by Initial Config during onboarding')
|
||||
} catch (e: any) {
|
||||
throw new CMError(`Accepted moderator invitation but error occurred while trying to set wiki config value from initial config (${initialConfig})`, {cause: e});
|
||||
}
|
||||
|
||||
// it's ok if this fails because we've already done all the onboarding steps. user can still access the dashboard and all settings have been applied (even if they were invalid IE config)
|
||||
manager.parseConfiguration('system', true).catch((err: any) => {
|
||||
if(err.logged !== true) {
|
||||
this.logger.error(err, {subreddit: manager.displayLabel});
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch(e: any) {
|
||||
throw e;
|
||||
} finally {
|
||||
await this.deleteSubredditInvite(invite);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteSubredditInvite(val: string | SubredditInvite) {
|
||||
let invite: SubredditInvite;
|
||||
if(val instanceof SubredditInvite) {
|
||||
invite = val;
|
||||
} else {
|
||||
const maybeInvite = this.botEntity.getSubredditInvites().find(x => x.subreddit === val);
|
||||
if(maybeInvite === undefined) {
|
||||
throw new CMError(`No invite for subreddit ${val} exists for this Bot`);
|
||||
}
|
||||
invite = maybeInvite;
|
||||
}
|
||||
await this.subredditInviteRepo.delete({id: invite.id});
|
||||
this.botEntity.removeSubredditInvite(invite);
|
||||
}
|
||||
}
|
||||
|
||||
export default Bot;
|
||||
|
||||
@@ -222,14 +222,7 @@ export abstract class Check extends RunnableBase implements Omit<ICheck, 'postTr
|
||||
this.actions.push(actionFactory({
|
||||
...aj,
|
||||
dryRun: this.dryRun || aj.dryRun
|
||||
}, {
|
||||
logger: this.logger,
|
||||
subredditName,
|
||||
resources: this.resources,
|
||||
client: this.client,
|
||||
emitter: this.emitter,
|
||||
checkName: this.name
|
||||
}));
|
||||
}, this.logger, subredditName, this.resources, this.client, this.emitter));
|
||||
// @ts-ignore
|
||||
a.logger = this.logger;
|
||||
} else {
|
||||
@@ -571,7 +564,7 @@ export abstract class Check extends RunnableBase implements Omit<ICheck, 'postTr
|
||||
const dr = dryRun || this.dryRun;
|
||||
this.logger.debug(`${dr ? 'DRYRUN - ' : ''}Running Actions`);
|
||||
for (const a of this.actions) {
|
||||
const res = await a.handle(item, ruleResults, runActions, options);
|
||||
const res = await a.handle(item, ruleResults, options);
|
||||
runActions.push(res);
|
||||
}
|
||||
this.logger.info(`${dr ? 'DRYRUN - ' : ''}Ran Actions: ${runActions.map(x => x.premise.getFriendlyIdentifier()).join(' | ')}`);
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import {ActivitySourceData, ActivitySourceTypes} from "./Infrastructure/Atomic";
|
||||
import {strToActivitySourceData} from "../util";
|
||||
|
||||
export class ActivitySource {
|
||||
type: ActivitySourceTypes
|
||||
identifier?: string
|
||||
|
||||
constructor(data: string | ActivitySourceData) {
|
||||
if (typeof data === 'string') {
|
||||
const {type, identifier} = strToActivitySourceData(data);
|
||||
this.type = type;
|
||||
this.identifier = identifier;
|
||||
} else {
|
||||
this.type = data.type;
|
||||
this.identifier = data.identifier;
|
||||
}
|
||||
}
|
||||
|
||||
matches(desired: ActivitySource): boolean {
|
||||
if(desired.type !== this.type) {
|
||||
return false;
|
||||
}
|
||||
// if this source does not have an identifier (we have already matched type) then it is broad enough to match
|
||||
if(this.identifier === undefined) {
|
||||
return true;
|
||||
}
|
||||
// at this point we know this source has an identifier but desired DOES NOT so this source is more restrictive and does not match
|
||||
if(desired.identifier === undefined) {
|
||||
return false;
|
||||
}
|
||||
// otherwise sources match if identifiers are the same
|
||||
return this.identifier.toLowerCase() === desired.identifier.toLowerCase();
|
||||
}
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
import {CacheProvider} from "../Infrastructure/Atomic";
|
||||
import {CacheOptions, StrongTTLConfig} from "../interfaces";
|
||||
import {cacheOptDefaults} from "../defaults";
|
||||
import cacheManager, {Cache, CachingConfig, WrapArgsType} from "cache-manager";
|
||||
import redisStore from "cache-manager-redis-store";
|
||||
import {create as createMemoryStore} from "../../Utils/memoryStore";
|
||||
import winston, {Logger} from "winston";
|
||||
import {mergeArr, parseStringToRegex, redisScanIterator} from "../../util";
|
||||
import globrex from "globrex";
|
||||
import objectHash from "object-hash";
|
||||
|
||||
export const buildCacheOptionsFromProvider = (provider: CacheProvider | any): CacheOptions => {
|
||||
if (typeof provider === 'string') {
|
||||
return {
|
||||
store: provider as CacheProvider,
|
||||
...cacheOptDefaults
|
||||
}
|
||||
}
|
||||
return {
|
||||
store: 'memory',
|
||||
...cacheOptDefaults,
|
||||
...provider,
|
||||
}
|
||||
}
|
||||
export const createCacheManager = (options: CacheOptions): Cache => {
|
||||
const {store, max, ttl = 60, host = 'localhost', port, auth_pass, db, prefix, ...rest} = options;
|
||||
switch (store) {
|
||||
case 'none':
|
||||
return cacheManager.caching({store: 'none', max, ttl});
|
||||
case 'redis':
|
||||
return cacheManager.caching({
|
||||
store: redisStore,
|
||||
host,
|
||||
port,
|
||||
auth_pass,
|
||||
db,
|
||||
ttl,
|
||||
...rest,
|
||||
});
|
||||
case 'memory':
|
||||
default:
|
||||
//return cacheManager.caching({store: 'memory', max, ttl});
|
||||
return cacheManager.caching({store: {create: createMemoryStore}, max, ttl, shouldCloneBeforeSet: false});
|
||||
}
|
||||
}
|
||||
|
||||
export class CMCache {
|
||||
pruneInterval?: any;
|
||||
prefix?: string
|
||||
cache: Cache
|
||||
isDefaultCache: boolean
|
||||
defaultPrefix?: string
|
||||
providerOptions: CacheOptions;
|
||||
logger!: Logger;
|
||||
|
||||
constructor(cache: Cache, providerOptions: CacheOptions, defaultCache: boolean, defaultPrefix: string | undefined, ttls: Partial<StrongTTLConfig>, logger: Logger) {
|
||||
this.cache = cache;
|
||||
this.providerOptions = providerOptions
|
||||
this.isDefaultCache = defaultCache;
|
||||
this.prefix = this.providerOptions.prefix ?? '';
|
||||
this.defaultPrefix = defaultPrefix ?? '';
|
||||
|
||||
this.setLogger(logger);
|
||||
|
||||
this.setPruneInterval(ttls);
|
||||
}
|
||||
|
||||
setLogger(logger: Logger) {
|
||||
this.logger = logger.child({labels: ['Cache']}, mergeArr);
|
||||
}
|
||||
|
||||
equalProvider(candidate: CacheOptions) {
|
||||
return objectHash.sha1(candidate) === objectHash.sha1(this.providerOptions);
|
||||
}
|
||||
|
||||
setPruneInterval(ttls: Partial<StrongTTLConfig>) {
|
||||
if (this.providerOptions.store === 'memory' && !this.isDefaultCache) {
|
||||
if (this.pruneInterval !== undefined) {
|
||||
clearInterval(this.pruneInterval);
|
||||
}
|
||||
const min = Math.min(60, ...Object.values(ttls).filter(x => typeof x === 'number' && x !== 0) as number[]);
|
||||
if (min > 0) {
|
||||
// set default prune interval
|
||||
this.pruneInterval = setInterval(() => {
|
||||
// @ts-ignore
|
||||
this.cache?.store.prune();
|
||||
this.logger.debug('Pruned cache');
|
||||
// prune interval should be twice the smallest TTL
|
||||
}, min * 1000 * 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getCacheKeyCount() {
|
||||
if (this.cache.store.keys !== undefined) {
|
||||
if (this.providerOptions.store === 'redis') {
|
||||
const keys = await this.cache.store.keys(`${this.prefix}*`);
|
||||
return keys.length;
|
||||
}
|
||||
return (await this.cache.store.keys()).length;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
async interactWithCacheByKeyPattern(pattern: string | RegExp, action: 'get' | 'delete') {
|
||||
let patternIsReg = pattern instanceof RegExp;
|
||||
let regPattern: RegExp;
|
||||
let globPattern = pattern;
|
||||
|
||||
const cacheDict: Record<string, any> = {};
|
||||
|
||||
if (typeof pattern === 'string') {
|
||||
const possibleRegPattern = parseStringToRegex(pattern, 'ig');
|
||||
if (possibleRegPattern !== undefined) {
|
||||
regPattern = possibleRegPattern;
|
||||
patternIsReg = true;
|
||||
} else {
|
||||
if (this.prefix !== undefined && !pattern.includes(this.prefix)) {
|
||||
// need to add wildcard to beginning of pattern so that the regex will still match a key with a prefix
|
||||
globPattern = `${this.prefix}${pattern}`;
|
||||
}
|
||||
// @ts-ignore
|
||||
const result = globrex(globPattern, {flags: 'i'});
|
||||
regPattern = result.regex;
|
||||
}
|
||||
} else {
|
||||
regPattern = pattern;
|
||||
}
|
||||
|
||||
if (this.providerOptions.store === 'redis') {
|
||||
// @ts-ignore
|
||||
const redisClient = this.cache.store.getClient();
|
||||
if (patternIsReg) {
|
||||
// scan all and test key by regex
|
||||
for await (const key of redisClient.scanIterator()) {
|
||||
if (regPattern.test(key) && (this.prefix === undefined || key.includes(this.prefix))) {
|
||||
if (action === 'delete') {
|
||||
await redisClient.del(key)
|
||||
} else {
|
||||
cacheDict[key] = await redisClient.get(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// not a regex means we can use glob pattern (more efficient!)
|
||||
for await (const key of redisScanIterator(redisClient, {MATCH: globPattern})) {
|
||||
if (action === 'delete') {
|
||||
await redisClient.del(key)
|
||||
} else {
|
||||
cacheDict[key] = await redisClient.get(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (this.cache.store.keys !== undefined) {
|
||||
for (const key of await this.cache.store.keys()) {
|
||||
if (regPattern.test(key) && (this.prefix === undefined || key.includes(this.prefix))) {
|
||||
if (action === 'delete') {
|
||||
await this.cache.del(key)
|
||||
} else {
|
||||
cacheDict[key] = await this.cache.get(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return cacheDict;
|
||||
}
|
||||
|
||||
async deleteCacheByKeyPattern(pattern: string | RegExp) {
|
||||
return await this.interactWithCacheByKeyPattern(pattern, 'delete');
|
||||
}
|
||||
|
||||
async getCacheByKeyPattern(pattern: string | RegExp) {
|
||||
return await this.interactWithCacheByKeyPattern(pattern, 'get');
|
||||
}
|
||||
|
||||
get store() {
|
||||
return this.cache.store;
|
||||
}
|
||||
|
||||
del(key: string, shared = false): Promise<any> {
|
||||
return this.cache.del(`${shared ? this.defaultPrefix : this.prefix}${key}`);
|
||||
}
|
||||
|
||||
get<T>(key: string, shared = false): Promise<T | undefined> {
|
||||
return this.cache.get(`${shared ? this.defaultPrefix : this.prefix}${key}`);
|
||||
}
|
||||
|
||||
reset(): Promise<void> {
|
||||
return this.cache.reset();
|
||||
}
|
||||
|
||||
set<T>(key: string, value: T, options?: CachingConfig & {shared?: boolean}): Promise<T> {
|
||||
const {shared = false} = options || {};
|
||||
return this.cache.set(`${shared ? this.defaultPrefix : this.prefix}${key}`, value, options);
|
||||
}
|
||||
|
||||
wrap<T>(...args: WrapArgsType<T>[]): Promise<T> {
|
||||
const options: any = args.length >= 3 ? args[2] : {};
|
||||
const {shared = false} = options || {};
|
||||
args[0] = `${shared ? this.defaultPrefix : this.prefix}${args[0]}`;
|
||||
return this.cache.wrap(...args);
|
||||
}
|
||||
|
||||
async destroy() {
|
||||
if (this.pruneInterval !== undefined && this.providerOptions.store === 'memory' && !this.isDefaultCache) {
|
||||
clearInterval(this.pruneInterval);
|
||||
this.cache?.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,11 +56,6 @@ export class ActionResultEntity extends TimeAwareRandomBaseEntity {
|
||||
@JoinColumn({name: 'premiseId'})
|
||||
premise!: ActionPremise;
|
||||
|
||||
/**
|
||||
* Ephemeral -- only added during actual run time and used for action templating. Is not available after loading from DB.
|
||||
* */
|
||||
data?: any;
|
||||
|
||||
touchedEntities: (Submission | Comment | RedditUser | string)[] = []
|
||||
|
||||
set itemIs(data: ActivityStateFilterResult | IFilterResult<TypedActivityState> | undefined) {
|
||||
|
||||
@@ -65,26 +65,4 @@ export class Bot extends RandomIdBaseEntity implements HasGuests {
|
||||
this.guests = []
|
||||
return [];
|
||||
}
|
||||
|
||||
getSubredditInvites(): SubredditInvite[] {
|
||||
if(this.subredditInvites === undefined) {
|
||||
return [];
|
||||
}
|
||||
return this.subredditInvites;
|
||||
}
|
||||
|
||||
addSubredditInvite(invite: SubredditInvite) {
|
||||
if(this.subredditInvites === undefined) {
|
||||
this.subredditInvites = [];
|
||||
}
|
||||
this.subredditInvites.push(invite);
|
||||
}
|
||||
|
||||
removeSubredditInvite(invite: SubredditInvite) {
|
||||
if(this.subredditInvites === undefined) {
|
||||
return;
|
||||
}
|
||||
const index = this.subredditInvites.findIndex(x => x.id === invite.id);
|
||||
this.subredditInvites.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import Submission from "snoowrap/dist/objects/Submission";
|
||||
import Comment from "snoowrap/dist/objects/Comment";
|
||||
import {ColumnDurationTransformer} from "./Transformers";
|
||||
import { RedditUser } from "snoowrap/dist/objects";
|
||||
import {ActivitySourceTypes, DurationVal, NonDispatchActivitySourceValue, onExistingFoundBehavior} from "../Infrastructure/Atomic";
|
||||
import {ActivitySourceTypes, DurationVal, NonDispatchActivitySource, onExistingFoundBehavior} from "../Infrastructure/Atomic";
|
||||
|
||||
@Entity({name: 'DispatchedAction'})
|
||||
export class DispatchedEntity extends TimeAwareRandomBaseEntity {
|
||||
@@ -53,7 +53,7 @@ export class DispatchedEntity extends TimeAwareRandomBaseEntity {
|
||||
identifier?: string
|
||||
|
||||
@Column("varchar", {nullable: true, length: 200})
|
||||
cancelIfQueued?: boolean | NonDispatchActivitySourceValue | NonDispatchActivitySourceValue[]
|
||||
cancelIfQueued?: boolean | NonDispatchActivitySource | NonDispatchActivitySource[]
|
||||
|
||||
@Column({nullable: true})
|
||||
onExistingFound?: onExistingFoundBehavior
|
||||
@@ -127,7 +127,7 @@ export class DispatchedEntity extends TimeAwareRandomBaseEntity {
|
||||
} else if (cVal === 'false') {
|
||||
this.cancelIfQueued = false;
|
||||
} else if (cVal.includes('[')) {
|
||||
this.cancelIfQueued = JSON.parse(cVal) as NonDispatchActivitySourceValue[];
|
||||
this.cancelIfQueued = JSON.parse(cVal) as NonDispatchActivitySource[];
|
||||
}
|
||||
}
|
||||
if(this.goto === null) {
|
||||
|
||||
@@ -43,7 +43,7 @@ export class ManagerEntity extends RandomIdBaseEntity implements RunningStateEnt
|
||||
@Column("varchar", {length: 200})
|
||||
name!: string;
|
||||
|
||||
@ManyToOne(type => Bot, sub => sub.managers, {eager: true})
|
||||
@ManyToOne(type => Bot, sub => sub.managers, {cascade: ['insert'], eager: true})
|
||||
bot!: Bot;
|
||||
|
||||
@ManyToOne(type => Subreddit, sub => sub.activities, {cascade: ['insert'], eager: true})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {AfterLoad, Column, Entity, JoinColumn, ManyToOne, PrimaryColumn} from "typeorm";
|
||||
import {InviteData, SubredditInviteData, SubredditInviteDataPersisted} from "../../Web/Common/interfaces";
|
||||
import {Column, Entity, JoinColumn, ManyToOne, PrimaryColumn} from "typeorm";
|
||||
import {InviteData, SubredditInviteData} from "../../Web/Common/interfaces";
|
||||
import dayjs, {Dayjs} from "dayjs";
|
||||
import {TimeAwareRandomBaseEntity} from "./Base/TimeAwareRandomBaseEntity";
|
||||
import {AuthorEntity} from "./AuthorEntity";
|
||||
@@ -8,7 +8,6 @@ import {Bot} from "./Bot";
|
||||
@Entity()
|
||||
export class SubredditInvite extends TimeAwareRandomBaseEntity implements SubredditInviteData {
|
||||
|
||||
@PrimaryColumn("varchar", {length: 255})
|
||||
subreddit!: string;
|
||||
|
||||
@Column("simple-json", {nullable: true})
|
||||
@@ -17,9 +16,6 @@ export class SubredditInvite extends TimeAwareRandomBaseEntity implements Subred
|
||||
@Column("text")
|
||||
initialConfig?: string
|
||||
|
||||
@PrimaryColumn("varchar", {length: 200})
|
||||
messageId?: string
|
||||
|
||||
@ManyToOne(type => Bot, bot => bot.subredditInvites, {nullable: false, orphanedRowAction: 'delete'})
|
||||
@JoinColumn({name: 'botId', referencedColumnName: 'id'})
|
||||
bot!: Bot;
|
||||
@@ -42,13 +38,12 @@ export class SubredditInvite extends TimeAwareRandomBaseEntity implements Subred
|
||||
}
|
||||
}
|
||||
|
||||
constructor(data?: SubredditInviteData & { expiresIn?: number, bot: Bot }) {
|
||||
constructor(data?: SubredditInviteData & { expiresIn?: number }) {
|
||||
super();
|
||||
if (data !== undefined) {
|
||||
this.subreddit = data.subreddit;
|
||||
this.initialConfig = data.initialConfig === null ? undefined : data.initialConfig;
|
||||
this.guests = data.guests === null || data.guests === undefined ? [] : data.guests;
|
||||
this.bot = data.bot;
|
||||
this.initialConfig = data.initialConfig;
|
||||
this.guests = data.guests;
|
||||
|
||||
|
||||
if (data.expiresIn !== undefined && data.expiresIn !== 0) {
|
||||
@@ -56,44 +51,4 @@ export class SubredditInvite extends TimeAwareRandomBaseEntity implements Subred
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toSubredditInviteData(): SubredditInviteDataPersisted {
|
||||
return {
|
||||
id: this.id,
|
||||
subreddit: this.subreddit,
|
||||
initialConfig: this.getInitialConfig(),
|
||||
guests: this.getGuests(),
|
||||
expiresAt: this.expiresAt !== undefined ? this.expiresAt.unix() : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
getGuests(): string[] {
|
||||
if(this.guests === null || this.guests === undefined) {
|
||||
return [];
|
||||
}
|
||||
return this.guests;
|
||||
}
|
||||
|
||||
getInitialConfig(): string | undefined {
|
||||
if(this.initialConfig === null) {
|
||||
return undefined;
|
||||
}
|
||||
return this.initialConfig;
|
||||
}
|
||||
|
||||
canAutomaticallyAccept() {
|
||||
return this.getGuests().length === 0 && this.getInitialConfig() === undefined;
|
||||
// TODO setup inbox checking to look for reply to messageId (eventually!)
|
||||
}
|
||||
|
||||
@AfterLoad()
|
||||
fixNullable() {
|
||||
if(this.guests === null) {
|
||||
this.guests = undefined;
|
||||
}
|
||||
if(this.initialConfig === null) {
|
||||
this.initialConfig = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,40 +1,16 @@
|
||||
import {InfluxConfig} from "./interfaces";
|
||||
import {InfluxDB, Point, WriteApi, setLogger, DEFAULT_WriteOptions, ClientOptions, DEFAULT_RetryDelayStrategyOptions, Logger as InfluxLogger} from "@influxdata/influxdb-client";
|
||||
import {InfluxDB, Point, WriteApi, setLogger} from "@influxdata/influxdb-client";
|
||||
import {HealthAPI} from "@influxdata/influxdb-client-apis";
|
||||
import dayjs, {Dayjs} from "dayjs";
|
||||
import {Logger} from "winston";
|
||||
import {mergeArr} from "../../util";
|
||||
import {CMError} from "../../Utils/Errors";
|
||||
import {Agent} from 'http';
|
||||
import {WriteOptions} from "@influxdata/influxdb-client/dist";
|
||||
|
||||
export interface InfluxClientConfig extends InfluxConfig {
|
||||
client?: InfluxDB
|
||||
ready?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Suppress non-error write failures
|
||||
*
|
||||
* These have not yet hit the max retry. On max retry failure Influx logs as ERROR.
|
||||
* The non-error failures are super noisy in the log so suppress them UNLESS debug is turned on
|
||||
*
|
||||
* https://github.com/influxdata/influxdb-client-js/blob/master/packages/core/src/impl/WriteApiImpl.ts#L221
|
||||
* */
|
||||
const extendLogger = (logger: Logger, suppressWriteWarnings = true): InfluxLogger => {
|
||||
return {
|
||||
...logger,
|
||||
error: (message: string, err?: any) => logger.error(message, err),
|
||||
warn: (message: string, err?: any) => {
|
||||
if(suppressWriteWarnings && !message.includes('Write to InfluxDB failed (attempt')) {
|
||||
logger.warn(message, err);
|
||||
} else if(!suppressWriteWarnings) {
|
||||
logger.warn(message, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class InfluxClient {
|
||||
config: InfluxConfig;
|
||||
client: InfluxDB;
|
||||
@@ -58,14 +34,13 @@ export class InfluxClient {
|
||||
|
||||
this.config = rest;
|
||||
this.ready = ready;
|
||||
if (client !== undefined) {
|
||||
if(client !== undefined) {
|
||||
this.client = client;
|
||||
} else {
|
||||
this.client = InfluxClient.createClient(this.config);
|
||||
setLogger(extendLogger(this.logger, !(rest.debug ?? false)));
|
||||
this.client = InfluxClient.createClient(this.config);
|
||||
setLogger(this.logger);
|
||||
}
|
||||
|
||||
this.write = this.client.getWriteApi(config.credentials.org, config.credentials.bucket, 'ms', InfluxClient.createWriteOptions(this.config, this.logger));
|
||||
this.write = this.client.getWriteApi(config.credentials.org, config.credentials.bucket, 'ms');
|
||||
this.tags = tags;
|
||||
this.write.useDefaultTags(tags);
|
||||
this.health = new HealthAPI(this.client);
|
||||
@@ -121,62 +96,13 @@ export class InfluxClient {
|
||||
}
|
||||
|
||||
static createClient(config: InfluxConfig): InfluxDB {
|
||||
const {
|
||||
credentials,
|
||||
useKeepAliveAgent = true,
|
||||
} = config;
|
||||
|
||||
const clientOptions: ClientOptions = {
|
||||
url: credentials.url,
|
||||
token: credentials.token,
|
||||
writeOptions: InfluxClient.createWriteOptions(config),
|
||||
}
|
||||
if (useKeepAliveAgent) {
|
||||
// reusing connection
|
||||
// https://github.com/influxdata/influxdb-client-js/issues/393#issuecomment-985272866
|
||||
const agent = new Agent({
|
||||
keepAlive: true,
|
||||
keepAliveMsecs: 20 * 1000, // 20 seconds keep alive
|
||||
})
|
||||
process.on('exit', () => agent.destroy())
|
||||
clientOptions.transportOptions = {agent};
|
||||
}
|
||||
return new InfluxDB(clientOptions);
|
||||
}
|
||||
|
||||
static createWriteOptions(config: InfluxConfig, logger?: Logger): Partial<WriteOptions> {
|
||||
const {
|
||||
return new InfluxDB({
|
||||
url: config.credentials.url,
|
||||
token: config.credentials.token,
|
||||
writeOptions: {
|
||||
defaultTags: userDefinedDefaultTags = {},
|
||||
...restUserWriteOptions
|
||||
} = {
|
||||
batchSize: 500,
|
||||
maxRetries: 5,
|
||||
// 30 seconds
|
||||
flushInterval: 30000
|
||||
},
|
||||
defaultTags: legacyDefaultTags = {},
|
||||
debug = false,
|
||||
} = config;
|
||||
|
||||
const allUserDefinedTags = {...legacyDefaultTags, ...userDefinedDefaultTags};
|
||||
|
||||
const writeOptions: Partial<WriteOptions> = {
|
||||
...DEFAULT_WriteOptions,
|
||||
...restUserWriteOptions,
|
||||
defaultTags: allUserDefinedTags
|
||||
}
|
||||
|
||||
if (debug && logger !== undefined) {
|
||||
writeOptions.writeSuccess = (lines: Array<string>) => {
|
||||
logger.debug(`Flushed ${lines.length} lines to server`);
|
||||
};
|
||||
writeOptions.writeRetrySkipped = (entry: { lines: Array<string>; expires: number }) => {
|
||||
logger.warn(`Skipped flushing ${entry.lines.length} lines due to full buffer`);
|
||||
defaultTags: config.defaultTags
|
||||
}
|
||||
}
|
||||
|
||||
return writeOptions;
|
||||
});
|
||||
}
|
||||
|
||||
childClient(logger: Logger, tags: Record<string, string> = {}) {
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import {InfluxDB, WriteApi, WriteOptions} from "@influxdata/influxdb-client/dist";
|
||||
import {InfluxDB, WriteApi} from "@influxdata/influxdb-client/dist";
|
||||
|
||||
export interface InfluxConfig {
|
||||
credentials: InfluxCredentials
|
||||
defaultTags?: Record<string, string>
|
||||
writeOptions?: WriteOptions
|
||||
useKeepAliveAgent?: boolean
|
||||
debug?: boolean
|
||||
}
|
||||
|
||||
export interface InfluxCredentials {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import {ActivityType} from "./Reddit";
|
||||
|
||||
/**
|
||||
* A duration and how to compare it against a value
|
||||
*
|
||||
@@ -17,22 +15,6 @@ import {ActivityType} from "./Reddit";
|
||||
|
||||
export type DurationComparor = string;
|
||||
|
||||
/**
|
||||
* A relative datetime description
|
||||
*
|
||||
* May be either:
|
||||
*
|
||||
* * day of the week (monday, tuesday, etc...)
|
||||
* * cron expression IE `* * 15 *`
|
||||
*
|
||||
* See https://crontab.guru/ for generating expressions
|
||||
*
|
||||
* https://regexr.com/6u3cc
|
||||
*
|
||||
* @pattern ((?:(?:(?:(?:\d+,)+\d+|(?:\d+(?:\/|-|#)\d+)|\d+L?|\*(?:\/\d+)?|L(?:-\d+)?|\?|[A-Z]{3}(?:-[A-Z]{3})?) ?){5,7})$)|(mon|tues|wed|thurs|fri|sat|sun){1}
|
||||
* */
|
||||
export type RelativeDateTimeMatch = string;
|
||||
|
||||
/**
|
||||
* A string containing a comparison operator and a value to compare against
|
||||
*
|
||||
@@ -41,7 +23,7 @@ export type RelativeDateTimeMatch = string;
|
||||
* * EX `> 100` => greater than 100
|
||||
* * EX `<= 75%` => less than or equal to 75%
|
||||
*
|
||||
* @pattern ^\s*(>|>=|<|<=)\s*((?:\d+)(?:(?:(?:.|,)\d+)+)?)\s*(%?)(.*)$
|
||||
* @pattern ^\s*(>|>=|<|<=)\s*(\d+)\s*(%?)(.*)$
|
||||
* */
|
||||
export type CompareValueOrPercent = string;
|
||||
export type StringOperator = '>' | '>=' | '<' | '<=';
|
||||
@@ -168,16 +150,9 @@ export type onExistingFoundBehavior = 'replace' | 'skip' | 'ignore';
|
||||
export type ActionTarget = 'self' | 'parent';
|
||||
export type ArbitraryActionTarget = ActionTarget | string;
|
||||
export type InclusiveActionTarget = ActionTarget | 'any';
|
||||
export const SOURCE_POLL = 'poll';
|
||||
export type SourcePollStr = 'poll';
|
||||
export const SOURCE_DISPATCH = 'dispatch';
|
||||
export type SourceDispatchStr = 'dispatch';
|
||||
export const SOURCE_USER = 'user';
|
||||
export type SourceUserStr = 'user';
|
||||
|
||||
export type DispatchSourceValue = SourceDispatchStr | `dispatch:${string}`;
|
||||
export type NonDispatchActivitySourceValue = SourcePollStr | `poll:${PollOn}` | SourceUserStr | `user:${string}`;
|
||||
export type ActivitySourceTypes = SourcePollStr | SourceDispatchStr | SourceUserStr; // TODO
|
||||
export type DispatchSource = 'dispatch' | `dispatch:${string}`;
|
||||
export type NonDispatchActivitySource = 'poll' | `poll:${PollOn}` | 'user' | `user:${string}`;
|
||||
export type ActivitySourceTypes = 'poll' | 'dispatch' | 'user'; // TODO
|
||||
// https://github.com/YousefED/typescript-json-schema/issues/426
|
||||
// https://github.com/YousefED/typescript-json-schema/issues/425
|
||||
// @pattern ^(((poll|dispatch)(:\w+)?)|user)$
|
||||
@@ -195,12 +170,7 @@ export type ActivitySourceTypes = SourcePollStr | SourceDispatchStr | SourceUser
|
||||
*
|
||||
*
|
||||
* */
|
||||
export type ActivitySourceValue = NonDispatchActivitySourceValue | DispatchSourceValue;
|
||||
|
||||
export interface ActivitySourceData {
|
||||
type: ActivitySourceTypes
|
||||
identifier?: string
|
||||
}
|
||||
export type ActivitySource = NonDispatchActivitySource | DispatchSource;
|
||||
|
||||
export type ConfigFormat = 'json' | 'yaml';
|
||||
export type ActionTypes =
|
||||
@@ -294,7 +264,7 @@ export type UserNoteType =
|
||||
|
||||
export const userNoteTypes = ['gooduser', 'spamwatch', 'spamwarn', 'abusewarn', 'ban', 'permban', 'botban'];
|
||||
|
||||
export type ConfigFragmentParseFunc = (data: object, fetched: boolean, subreddit?: string) => object | object[];
|
||||
export type ConfigFragmentValidationFunc = (data: object, fetched: boolean) => boolean;
|
||||
|
||||
export interface WikiContext {
|
||||
wiki: string
|
||||
@@ -314,84 +284,3 @@ export interface ImageHashCacheData {
|
||||
original?: string
|
||||
flipped?: string
|
||||
}
|
||||
|
||||
// https://www.reddit.com/message/compose?to=/r/mealtimevideos&message=https://www.reddit.com/r/ContextModBot/comments/otz396/introduction_to_contextmodbot
|
||||
|
||||
export interface BaseTemplateData {
|
||||
botLink: string
|
||||
modmailLink?: string
|
||||
manager?: string
|
||||
check?: string
|
||||
//[key: string]: any
|
||||
}
|
||||
|
||||
export interface ActivityTemplateData {
|
||||
kind: ActivityType
|
||||
author: string
|
||||
votes: number
|
||||
age: string
|
||||
permalink: string
|
||||
id: string
|
||||
subreddit: string
|
||||
title: string
|
||||
shortTitle: string
|
||||
}
|
||||
|
||||
export interface ModdedActivityTemplateData {
|
||||
reports: number
|
||||
modReports: number
|
||||
userReports: number
|
||||
}
|
||||
|
||||
export interface SubmissionTemplateData extends ActivityTemplateData, Partial<ModdedActivityTemplateData> {
|
||||
nsfw: boolean
|
||||
spoiler: boolean
|
||||
op: boolean
|
||||
upvoteRatio: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface CommentTemplateData extends ActivityTemplateData, Partial<ModdedActivityTemplateData> {
|
||||
op: boolean
|
||||
}
|
||||
|
||||
export interface SubredditTemplateData {
|
||||
subredditBreakdownFormatted: string
|
||||
subredditBreakdown?: {
|
||||
totalFormatted: string
|
||||
submissionFormatted: string
|
||||
commentFormatted: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface RuleResultTemplateData {
|
||||
kind: string
|
||||
triggered: boolean
|
||||
result: string
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
export interface ActionResultTemplateData {
|
||||
kind: string
|
||||
success: boolean
|
||||
result: string
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
export interface ActionResultsTemplateData {
|
||||
actionSummary: string
|
||||
actions: {
|
||||
[key: string]: ActionResultTemplateData
|
||||
}
|
||||
}
|
||||
|
||||
export interface RuleResultsTemplateData {
|
||||
ruleSummary: string
|
||||
rules: {
|
||||
[key: string]: RuleResultTemplateData
|
||||
}
|
||||
}
|
||||
|
||||
export interface GenericContentTemplateData extends BaseTemplateData, Partial<RuleResultsTemplateData>, Partial<ActionResultsTemplateData> {
|
||||
item?: (SubmissionTemplateData | CommentTemplateData)
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ export const asGenericComparison = (val: any): val is GenericComparison => {
|
||||
return typeof val === 'object' && 'value' in val;
|
||||
}
|
||||
|
||||
export const GENERIC_VALUE_COMPARISON = /^\s*(?<opStr>>|>=|<|<=)\s*(?<value>-?(?:\d+)(?:(?:(?:.|,)\d+)+)?)(?<extra>\s+.*)*$/
|
||||
export const GENERIC_VALUE_COMPARISON_URL = 'https://regexr.com/6vama';
|
||||
export const GENERIC_VALUE_COMPARISON = /^\s*(?<opStr>>|>=|<|<=)\s*(?<value>-?\d?\.?\d+)(?<extra>\s+.*)*$/
|
||||
export const GENERIC_VALUE_COMPARISON_URL = 'https://regexr.com/60dq4';
|
||||
export const parseGenericValueComparison = (val: string, options?: {
|
||||
requireDuration?: boolean,
|
||||
reg?: RegExp
|
||||
@@ -107,8 +107,8 @@ export const parseGenericValueComparison = (val: string, options?: {
|
||||
durationText,
|
||||
}
|
||||
}
|
||||
const GENERIC_VALUE_PERCENT_COMPARISON = /^\s*(?<opStr>>|>=|<|<=)\s*(?<value>(?:\d+)(?:(?:(?:.|,)\d+)+)?)\s*(?<percent>%)?(?<extra>.*)$/
|
||||
const GENERIC_VALUE_PERCENT_COMPARISON_URL = 'https://regexr.com/6valr';
|
||||
const GENERIC_VALUE_PERCENT_COMPARISON = /^\s*(?<opStr>>|>=|<|<=)\s*(?<value>\d+)\s*(?<percent>%)?(?<extra>.*)$/
|
||||
const GENERIC_VALUE_PERCENT_COMPARISON_URL = 'https://regexr.com/60a16';
|
||||
export const parseGenericValueOrPercentComparison = (val: string, options?: {requireDuration: boolean}): GenericComparison => {
|
||||
return parseGenericValueComparison(val, {...(options ?? {}), reg: GENERIC_VALUE_PERCENT_COMPARISON});
|
||||
}
|
||||
|
||||
@@ -4,13 +4,11 @@ import {
|
||||
DurationComparor,
|
||||
ModeratorNameCriteria,
|
||||
ModeratorNames, ModActionType,
|
||||
ModUserNoteLabel, RelativeDateTimeMatch
|
||||
ModUserNoteLabel
|
||||
} from "../Atomic";
|
||||
import {ActivityType, MaybeActivityType} from "../Reddit";
|
||||
import {ActivityType} from "../Reddit";
|
||||
import {GenericComparison, parseGenericValueComparison} from "../Comparisons";
|
||||
import {parseStringToRegexOrLiteralSearch, toModNoteLabel} from "../../../util";
|
||||
import { Submission, Comment } from "snoowrap";
|
||||
import {RedditUser} from "snoowrap/dist/objects";
|
||||
import {parseStringToRegexOrLiteralSearch} from "../../../util";
|
||||
|
||||
/**
|
||||
* Different attributes a `Subreddit` can be in. Only include a property if you want to check it.
|
||||
@@ -120,49 +118,17 @@ export interface UserNoteCriteria extends UserSubredditHistoryCriteria {
|
||||
* @examples ["spamwarn"]
|
||||
* */
|
||||
type: string;
|
||||
/**
|
||||
* The content of the Note to search For.
|
||||
*
|
||||
* * Can be a single string or list of strings to search for. Each string will be searched for case-insensitive, as a subset of note content.
|
||||
* * Can also be Regular Expression if wrapped in forward slashes IE '\/test.*\/i'
|
||||
* */
|
||||
note?: string | string[]
|
||||
/*
|
||||
* Does this note link to the currently processing Activity?
|
||||
* */
|
||||
referencesCurrentActivity?: boolean
|
||||
}
|
||||
|
||||
export interface FullUserNoteCriteria extends Omit<UserNoteCriteria, 'note'> {
|
||||
note?: RegExp[]
|
||||
}
|
||||
|
||||
export const toFullUserNoteCriteria = (val: UserNoteCriteria): FullUserNoteCriteria => {
|
||||
const {note} = val;
|
||||
let notesVal = undefined;
|
||||
if (note !== undefined) {
|
||||
const notesArr = Array.isArray(note) ? note : [note];
|
||||
notesVal = notesArr.map(x => parseStringToRegexOrLiteralSearch(x));
|
||||
}
|
||||
return {
|
||||
...val,
|
||||
note: notesVal
|
||||
}
|
||||
}
|
||||
|
||||
export interface ModActionCriteria extends UserSubredditHistoryCriteria {
|
||||
type?: ModActionType | ModActionType[]
|
||||
activityType?: MaybeActivityType | MaybeActivityType[]
|
||||
referencesCurrentActivity?: boolean
|
||||
activityType?: ActivityType | ActivityType[]
|
||||
}
|
||||
|
||||
export interface FullModActionCriteria extends Omit<ModActionCriteria, 'count'> {
|
||||
type?: ModActionType[]
|
||||
count?: GenericComparison
|
||||
/*
|
||||
* Does this action/note link to the currently processing Activity?
|
||||
* */
|
||||
activityType?: MaybeActivityType[]
|
||||
activityType?: ActivityType[]
|
||||
}
|
||||
|
||||
export interface ModNoteCriteria extends ModActionCriteria {
|
||||
@@ -170,14 +136,8 @@ export interface ModNoteCriteria extends ModActionCriteria {
|
||||
note?: string | string[]
|
||||
}
|
||||
|
||||
export interface FullModNoteCriteria extends FullModActionCriteria {
|
||||
export interface FullModNoteCriteria extends FullModActionCriteria, Omit<ModNoteCriteria, 'note' | 'count' | 'type' | 'activityType'> {
|
||||
noteType?: ModUserNoteLabel[]
|
||||
/**
|
||||
* The content of the Note to search For.
|
||||
*
|
||||
* * Can be a single string or list of strings to search for. Each string will be searched for case-insensitive, as a subset of note content.
|
||||
* * Can also be Regular Expression if wrapped in forward slashes IE '\/test.*\/i'
|
||||
* */
|
||||
note?: RegExp[]
|
||||
}
|
||||
|
||||
@@ -206,16 +166,7 @@ export const toFullModNoteCriteria = (val: ModNoteCriteria): FullModNoteCriteria
|
||||
acc.count = parseGenericValueComparison(rawVal);
|
||||
break;
|
||||
case 'activityType':
|
||||
if(rawVal === false) {
|
||||
acc[k] = rawVal
|
||||
} else {
|
||||
acc[k] = rawVal.toLowerCase();
|
||||
}
|
||||
break;
|
||||
case 'noteType':
|
||||
acc[k] = rawVal.map((x: string) => toModNoteLabel(x));
|
||||
break;
|
||||
case 'referencesCurrentActivity':
|
||||
acc[k] = rawVal;
|
||||
break;
|
||||
case 'note':
|
||||
@@ -242,7 +193,7 @@ export interface FullModLogCriteria extends FullModActionCriteria, Omit<ModLogCr
|
||||
description?: RegExp[]
|
||||
}
|
||||
|
||||
const arrayableModLogProps = ['type','activityType','action','description','details'];
|
||||
const arrayableModLogProps = ['type','activityType','action','description','details', 'type'];
|
||||
|
||||
export const asModLogCriteria = (val: any): val is ModLogCriteria => {
|
||||
return val !== null && typeof val === 'object' && !asModNoteCriteria(val) && ('action' in val || 'details' in val || 'description' in val || 'activityType' in val || 'search' in val || 'count' in val || 'type' in val);
|
||||
@@ -267,17 +218,8 @@ export const toFullModLogCriteria = (val: ModLogCriteria): FullModLogCriteria =>
|
||||
acc.count = parseGenericValueComparison(rawVal);
|
||||
break;
|
||||
case 'activityType':
|
||||
if(rawVal === false) {
|
||||
acc[k] = rawVal
|
||||
} else {
|
||||
acc[k] = rawVal.toLowerCase();
|
||||
}
|
||||
break;
|
||||
case 'type':
|
||||
acc[k] = rawVal.map((x: string) => x.toUpperCase());
|
||||
break;
|
||||
case 'referencesCurrentActivity':
|
||||
acc[k] = rawVal;
|
||||
acc[k as keyof FullModLogCriteria] = rawVal;
|
||||
break;
|
||||
case 'action':
|
||||
case 'description':
|
||||
@@ -303,11 +245,10 @@ export const authorCriteriaProperties = ['name', 'flairCssClass', 'flairText', '
|
||||
* */
|
||||
export interface AuthorCriteria {
|
||||
/**
|
||||
* A list of reddit usernames (case-insensitive) or regular expressions to match against. Do not include the "u/" prefix
|
||||
*
|
||||
* A list of reddit usernames (case-insensitive) to match against. Do not include the "u/" prefix
|
||||
*
|
||||
* EX to match against /u/FoxxMD and /u/AnotherUser use ["FoxxMD","AnotherUser"]
|
||||
* @examples ["FoxxMD","AnotherUser", "/.*Foxx.\/*i"]
|
||||
* @examples ["FoxxMD","AnotherUser"]
|
||||
* */
|
||||
name?: string[],
|
||||
/**
|
||||
@@ -315,25 +256,14 @@ export interface AuthorCriteria {
|
||||
*
|
||||
* * If `true` then passes if ANY css is assigned
|
||||
* * If `false` then passes if NO css is assigned
|
||||
* * If string or list of strings then text is matched, case-insensitive. String may also be a regular expression enclosed in forward slashes.
|
||||
* @examples ["red"]
|
||||
* */
|
||||
flairCssClass?: boolean | string | string[],
|
||||
|
||||
/**
|
||||
* The (user) flair background color (or list of) from the subreddit to match against
|
||||
*
|
||||
* * If `true` then passes if ANY css background color is assigned
|
||||
* * If `false` then passes if NO css background is assigned
|
||||
* * If string or list of strings then color is matched, case-insensitive, without #. String may also be a regular expression enclosed in forward slashes.
|
||||
* */
|
||||
flairBackgroundColor?: boolean | string | string[],
|
||||
/**
|
||||
* A (user) flair text value (or list of) from the subreddit to match against
|
||||
*
|
||||
* * If `true` then passes if ANY text is assigned
|
||||
* * If `false` then passes if NO text is assigned
|
||||
* * If string or list of strings then text is matched, case-insensitive. String may also be a regular expression enclosed in forward slashes.
|
||||
*
|
||||
* @examples ["Approved"]
|
||||
* */
|
||||
@@ -344,7 +274,6 @@ export interface AuthorCriteria {
|
||||
*
|
||||
* * If `true` then passes if ANY template is assigned
|
||||
* * If `false` then passed if NO template is assigned
|
||||
* * If string or list of strings then text is matched, case-insensitive. String may also be a regular expression enclosed in forward slashes.
|
||||
*
|
||||
* */
|
||||
flairTemplate?: boolean | string | string[]
|
||||
@@ -511,21 +440,6 @@ export interface ActivityState {
|
||||
* */
|
||||
reports?: string
|
||||
age?: DurationComparor
|
||||
|
||||
/**
|
||||
* A relative datetime description to match the date the Activity was created
|
||||
*
|
||||
* May be either:
|
||||
*
|
||||
* * day of the week (monday, tuesday, etc...)
|
||||
* * cron expression IE `* * 15 *`
|
||||
*
|
||||
* See https://crontab.guru/ for generating expressions
|
||||
*
|
||||
* https://regexr.com/6u3cc
|
||||
*
|
||||
* */
|
||||
createdOn?: RelativeDateTimeMatch | RelativeDateTimeMatch[]
|
||||
/**
|
||||
* Test whether the activity is present in dispatched/delayed activities
|
||||
*
|
||||
@@ -555,33 +469,6 @@ export interface ActivityState {
|
||||
*
|
||||
* */
|
||||
source?: string | string[]
|
||||
|
||||
/**
|
||||
* * If `true` then passes if ANY flair
|
||||
* * If `false` then passes if NO flair
|
||||
* * If string or list of strings then text is matched, case-insensitive. String may also be a regular expression enclosed in forward slashes.
|
||||
* */
|
||||
authorFlairText?: boolean | string | string[]
|
||||
/**
|
||||
* * If `true` then passes if ANY flair
|
||||
* * If `false` then passes if NO flair
|
||||
* * If string or list of strings then template id is matched, case-insensitive. String may also be a regular expression enclosed in forward slashes.
|
||||
* */
|
||||
authorFlairTemplateId?: boolean | string | string[]
|
||||
|
||||
/**
|
||||
* * If `true` then passes if ANY class
|
||||
* * If `false` then passes if NO class
|
||||
* * If string or list of strings then class is matched, case-insensitive. String may also be a regular expression enclosed in forward slashes.
|
||||
* */
|
||||
authorFlairCssClass?: boolean | string | string[]
|
||||
|
||||
/**
|
||||
* * If `true` then passes if ANY color
|
||||
* * If `false` then passes if NO color
|
||||
* * If string or list of strings then color is matched, case-insensitive, without #. String may also be a regular expression enclosed in forward slashes.
|
||||
* */
|
||||
authorFlairBackgroundColor?: boolean | string | string[]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -604,22 +491,13 @@ export interface SubmissionState extends ActivityState {
|
||||
/**
|
||||
* * If `true` then passes if flair has ANY text
|
||||
* * If `false` then passes if flair has NO text
|
||||
* * If string or list of strings then text is matched, case-insensitive. String may also be a regular expression enclosed in forward slashes.
|
||||
* */
|
||||
link_flair_text?: boolean | string | string[]
|
||||
/**
|
||||
* * If `true` then passes if flair has ANY css
|
||||
* * If `false` then passes if flair has NO css
|
||||
* * If string or list of strings then class is matched, case-insensitive. String may also be a regular expression enclosed in forward slashes.
|
||||
* */
|
||||
link_flair_css_class?: boolean | string | string[]
|
||||
|
||||
/**
|
||||
* * If `true` then passes if ANY color
|
||||
* * If `false` then passes if NO color
|
||||
* * If string or list of strings then color is matched, case-insensitive, without #. String may also be a regular expression enclosed in forward slashes.
|
||||
* */
|
||||
link_flair_background_color?: boolean | string | string[]
|
||||
/**
|
||||
* * If `true` then passes if there is ANY flair template id
|
||||
* * If `false` then passes if there is NO flair template id
|
||||
@@ -643,23 +521,6 @@ export interface SubmissionState extends ActivityState {
|
||||
upvoteRatio?: number | CompareValue
|
||||
}
|
||||
|
||||
export const cmToSnoowrapActivityMap: Record<string, keyof (Submission & Comment)> = {
|
||||
authorFlairText: 'author_flair_text',
|
||||
flairText: 'author_flair_text',
|
||||
authorFlairTemplateId: 'author_flair_template_id',
|
||||
authorFlairCssClass: 'author_flair_css_class',
|
||||
authorFlairBackgroundColor: 'author_flair_background_color',
|
||||
flairTemplate: 'link_flair_template_id',
|
||||
flairCssClass: 'author_flair_css_class',
|
||||
}
|
||||
|
||||
export const cmToSnoowrapAuthorMap: Record<string, keyof (Submission & Comment)> = {
|
||||
flairText: 'author_flair_text',
|
||||
flairCssClass: 'author_flair_css_class',
|
||||
flairTemplate: 'author_flair_template_id',
|
||||
flairBackgroundColor: 'author_flair_background_color',
|
||||
}
|
||||
|
||||
export const cmActivityProperties = ['submissionState', 'score', 'reports', 'removed', 'deleted', 'filtered', 'age', 'title'];
|
||||
|
||||
/**
|
||||
|
||||
@@ -41,10 +41,6 @@ export interface FilterOptionsJson<T> {
|
||||
|
||||
}
|
||||
|
||||
export const asFilterOptionsJson = <T>(val: any): val is FilterOptionsJson<T> => {
|
||||
return val !== null && typeof val === 'object' && (val.include !== undefined || val.exclude !== undefined);
|
||||
}
|
||||
|
||||
export interface FilterOptionsConfig<T> extends FilterOptionsJson<T> {
|
||||
|
||||
/**
|
||||
@@ -70,7 +66,7 @@ export interface FilterOptions<T> extends FilterOptionsConfig<T> {
|
||||
|
||||
export type MinimalOrFullFilter<T> = MaybeAnonymousCriteria<T>[] | FilterOptions<T>
|
||||
export type MinimalOrFullMaybeAnonymousFilter<T> = MaybeAnonymousCriteria<T>[] | FilterOptionsConfig<T>
|
||||
export type MinimalOrFullFilterJson<T> = MaybeAnonymousOrStringCriteria<T> | MaybeAnonymousOrStringCriteria<T>[] | FilterOptionsJson<T>
|
||||
export type MinimalOrFullFilterJson<T> = MaybeAnonymousOrStringCriteria<T>[] | FilterOptionsJson<T>
|
||||
export type StructuredFilter<T> = Omit<T, 'authorIs' | 'itemIs'> & {
|
||||
itemIs?: MinimalOrFullFilter<TypedActivityState>
|
||||
authorIs?: MinimalOrFullFilter<AuthorCriteria>
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import {Comment, RedditUser, Submission, Subreddit} from "snoowrap/dist/objects";
|
||||
import { ValueOf } from "ts-essentials";
|
||||
import {CMError} from "../../Utils/Errors";
|
||||
import {Comment, Submission} from "snoowrap/dist/objects";
|
||||
|
||||
export type ActivityType = 'submission' | 'comment';
|
||||
export type MaybeActivityType = ActivityType | false;
|
||||
export type FullNameTypes = ActivityType | 'user' | 'subreddit' | 'message';
|
||||
|
||||
export interface RedditThing {
|
||||
@@ -23,22 +20,8 @@ export type AuthorHistorySortTime = 'hour' | 'day' | 'week' | 'month' | 'year' |
|
||||
export type AuthorHistoryType = 'comment' | 'submission' | 'overview';
|
||||
export type SnoowrapActivity = Submission | Comment;
|
||||
|
||||
type valueof<T> = T[keyof T]
|
||||
|
||||
/*
|
||||
* Depending on what caching provider is used the results from cache can either be
|
||||
*
|
||||
* * full-fat SnoowrapActivities (memory provider keeps everything in memory!)
|
||||
* * OR json-serialized objects of the data from those activities (all other cache providers)
|
||||
*
|
||||
* we don't know which they are until we retrieve them.
|
||||
* */
|
||||
export type SnoowrapLike = Record<keyof SnoowrapActivity, valueof<SnoowrapActivity>>;
|
||||
export type RedditUserLike = Record<keyof RedditUser, valueof<RedditUser>>;
|
||||
export type SubredditLike = Record<keyof Subreddit, valueof<Subreddit>>;
|
||||
|
||||
export interface CachedFetchedActivitiesResult {
|
||||
pre: SnoowrapActivity[] | SnoowrapLike[]
|
||||
pre: SnoowrapActivity[]
|
||||
rawCount: number
|
||||
apiCount: number
|
||||
preMaxTrigger?: string | null
|
||||
@@ -46,7 +29,6 @@ export interface CachedFetchedActivitiesResult {
|
||||
|
||||
export interface FetchedActivitiesResult extends CachedFetchedActivitiesResult {
|
||||
post: SnoowrapActivity[]
|
||||
pre: SnoowrapActivity[]
|
||||
}
|
||||
|
||||
export type ReportType = 'mod' | 'user';
|
||||
@@ -106,63 +88,3 @@ export interface SubredditRemovalReason {
|
||||
id: string,
|
||||
title: string
|
||||
}
|
||||
|
||||
export interface SubredditActivityAbsoluteBreakdown {
|
||||
count: number
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface SubredditActivityBreakdown extends SubredditActivityAbsoluteBreakdown {
|
||||
percent: number
|
||||
}
|
||||
|
||||
export interface SubredditActivityBreakdownByType {
|
||||
total: SubredditActivityBreakdown[]
|
||||
submission: SubredditActivityBreakdown[]
|
||||
comment: SubredditActivityBreakdown[]
|
||||
}
|
||||
|
||||
/**
|
||||
* * `comment` -> reply to activity with comment as with bot account
|
||||
* * `commentModTeam` -> reply to activity with comment "as subreddit" (modteam account)
|
||||
* * `modmail` -> send a modmail as the bot account
|
||||
* * `modmailSubreddit` -> send a modmial as the subrddit
|
||||
* */
|
||||
export type CMRemovalMessageType = 'comment' | 'commentModTeam' | 'modmailSubreddit' | 'modmail';
|
||||
export const cmRemovalMessageType = ['comment', 'commentModTeam', 'modmailSubreddit', 'modmail'];
|
||||
|
||||
export const toCmRemovalMessageType = (val: string): CMRemovalMessageType => {
|
||||
switch(val.toLowerCase()){
|
||||
case 'comment':
|
||||
return 'comment';
|
||||
case 'modmail':
|
||||
return 'modmail';
|
||||
case 'commentmodteam':
|
||||
return 'commentModTeam';
|
||||
case 'modmailsubreddit':
|
||||
return 'modmailSubreddit';
|
||||
default:
|
||||
throw new CMError(`Removal Message Type '${val}' was not recognized. Valid types: ${cmRemovalMessageType.join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
export type RedditRemovalMessageType = 'public' | 'private' | 'private_exposed' | 'public_as_subreddit';
|
||||
export const redditRemoveMessageTypes = ['public', 'private', 'private_exposed', 'public_as_subreddit'];
|
||||
|
||||
export const cmToRedditRemovalReason = (cmType: CMRemovalMessageType): RedditRemovalMessageType => {
|
||||
switch (cmType) {
|
||||
case 'comment':
|
||||
return 'public';
|
||||
case 'commentModTeam':
|
||||
return 'public_as_subreddit';
|
||||
case 'modmail':
|
||||
return 'private_exposed';
|
||||
case 'modmailSubreddit':
|
||||
return 'private';
|
||||
}
|
||||
}
|
||||
|
||||
export interface RedditRemovalMessageOptions {
|
||||
title?: string
|
||||
lock?: boolean
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import {MigrationInterface, QueryRunner, Table, TableColumn} from "typeorm"
|
||||
|
||||
export class subredditInvite1663001719622 implements MigrationInterface {
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
const table = await queryRunner.getTable('SubredditInvite') as Table;
|
||||
|
||||
await queryRunner.addColumns(table, [
|
||||
new TableColumn( {
|
||||
name: 'messageId',
|
||||
type: 'varchar',
|
||||
length: '200',
|
||||
isUnique: true,
|
||||
isNullable: true
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
}
|
||||
|
||||
}
|
||||