Initial commit
This commit is contained in:
commit
a5b305bef9
7 changed files with 470 additions and 0 deletions
287
.gitignore
vendored
Normal file
287
.gitignore
vendored
Normal file
|
@ -0,0 +1,287 @@
|
|||
# Created by https://www.toptal.com/developers/gitignore/api/pycharm+all,visualstudiocode,python
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=pycharm+all,visualstudiocode,python
|
||||
|
||||
### PyCharm+all ###
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/**/usage.statistics.xml
|
||||
.idea/**/dictionaries
|
||||
.idea/**/shelf
|
||||
|
||||
# AWS User-specific
|
||||
.idea/**/aws.xml
|
||||
|
||||
# Generated files
|
||||
.idea/**/contentModel.xml
|
||||
|
||||
# Sensitive or high-churn files
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
.idea/**/dbnavigator.xml
|
||||
|
||||
# Gradle
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# Gradle and Maven with auto-import
|
||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# since they will be recreated, and may cause churn. Uncomment if using
|
||||
# auto-import.
|
||||
# .idea/artifacts
|
||||
# .idea/compiler.xml
|
||||
# .idea/jarRepositories.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/*.iml
|
||||
# .idea/modules
|
||||
# *.iml
|
||||
# *.ipr
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
|
||||
# Mongo Explorer plugin
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
# File-based project format
|
||||
*.iws
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# SonarLint plugin
|
||||
.idea/sonarlint/
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
# Editor-based Rest Client
|
||||
.idea/httpRequests
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
### PyCharm+all Patch ###
|
||||
# Ignore everything but code style settings and run configurations
|
||||
# that are supposed to be shared within teams.
|
||||
|
||||
.idea/*
|
||||
|
||||
!.idea/codeStyles
|
||||
!.idea/runConfigurations
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
### Python Patch ###
|
||||
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
||||
poetry.toml
|
||||
|
||||
# ruff
|
||||
.ruff_cache/
|
||||
|
||||
# LSP config files
|
||||
pyrightconfig.json
|
||||
|
||||
### VisualStudioCode ###
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Built Visual Studio Code Extensions
|
||||
*.vsix
|
||||
|
||||
### VisualStudioCode Patch ###
|
||||
# Ignore all local history of files
|
||||
.history
|
||||
.ionide
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/pycharm+all,visualstudiocode,python
|
||||
config.ini
|
||||
.env
|
||||
notes.json
|
||||
.lastfetch
|
21
LICENSE
Normal file
21
LICENSE
Normal file
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2024 nexy7574 <https://https://codeberg.org/nexy7574>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
55
README.md
Normal file
55
README.md
Normal file
|
@ -0,0 +1,55 @@
|
|||
# Fediverse Admin Bot
|
||||
|
||||
This is a simple bot designed for misskey (and its forks) to redirect mentions and messages to an unmonitored `@admin` account
|
||||
to a monitored account.
|
||||
|
||||
For example, this bot is running under `@admin@fedi.transgender.ing` and redirects all mentions and messages to `@nex@fedi.transgender.ing`, and includes
|
||||
a link to the relevant matrix room. You can see the exact reply [in copy.txt](./copy.txt).
|
||||
|
||||
This bot requires an API key, and the ability to see notifications, create notes, and add reactions to notes. When bot.py is run, it will loop indefinitely,
|
||||
fetching new notifications and processing every minute (configurable).
|
||||
|
||||
## Installation
|
||||
|
||||
Simply clone the repository, or grab the latest release. Then, create a virtualenv, and install the requirements from requirements.txt.
|
||||
This bot was created with Python 3.12, however should be compatible with any version of Python 3.8 or above. It doesn't use any fancy syntax, at least.
|
||||
|
||||
### config.ini
|
||||
|
||||
Before you start, you'll need a `config.ini` in your working directory. This file should look like this:
|
||||
|
||||
```ini
|
||||
[domain.example] # the domain of the instance you're running on
|
||||
api_key = your_api_key
|
||||
sleep_time = 60 # how long to wait between loops, in seconds. Default is 1 minute, if omitted.
|
||||
limit = 100 # how many notifications to fetch at once.
|
||||
# If your admin account is getting an absurd amount of traffic, you may need to raise this to ensure that all notifications are processed.
|
||||
```
|
||||
|
||||
### `.lastfetch`
|
||||
|
||||
You need to make sure that the bot can read+write to the `./.lastfetch` - this file contains a string, which is the ID of the last fetched notification.
|
||||
Deleting this will cause the bot to reprocess the last `:limit:` notifications, which may result in double-posting.
|
||||
This file does not have to exist on startup, it will be created.
|
||||
Do not edit this file, unless you want to manually replace what the last fetched notification was.
|
||||
|
||||
If you have an ID you would like to use as the epoch, you can either manually write it to that file, or set it as the `$EPOCH_ID` environment variable.
|
||||
|
||||
### `bot.log`
|
||||
|
||||
The bot will automatically log all decisions it makes, timestamped, with a reason, to a file called `bot.log`. This file will be created if it does not exist.
|
||||
|
||||
**The log file does not automatically rotate.** If you want to keep logs for a long time, you will need to manually rotate them.
|
||||
The log file is also not overwritten on startup, it is automatically appended to. It is more of a black-box thing than a debugging tool.
|
||||
|
||||
#### Setting the log level
|
||||
|
||||
By default, the log level is set to `INFO`. If you want to change this, you can set the `LOGLEVEL` environment variable to one of the following:
|
||||
|
||||
* `DEBUG`
|
||||
* `INFO`
|
||||
* `WARNING`
|
||||
* `ERROR`
|
||||
* `CRITICAL`
|
||||
|
||||
Debug is the most verbose, critical is only for the most severe errors.
|
96
bot.py
Normal file
96
bot.py
Normal file
|
@ -0,0 +1,96 @@
|
|||
import time
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
import random
|
||||
from configparser import ConfigParser
|
||||
from misskey import Misskey
|
||||
from misskey.exceptions import MisskeyAPIException
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
filename="bot.log",
|
||||
filemode="a",
|
||||
level=getattr(logging, os.getenv("LOGLEVEL", "INFO")),
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("fedibot")
|
||||
|
||||
config = ConfigParser()
|
||||
config.read("config.ini")
|
||||
|
||||
server_domain = list(config.keys())[1]
|
||||
api_key = config[server_domain]["api_key"]
|
||||
sleep_time = int(config[server_domain].get("sleep_time", 60))
|
||||
limit = int(config[server_domain].get("limit", 100))
|
||||
|
||||
bot = Misskey(server_domain, api_key)
|
||||
|
||||
with open("./copy.txt") as _fd:
|
||||
copy = _fd.read()
|
||||
|
||||
|
||||
def main():
|
||||
print("Bot running.")
|
||||
while True:
|
||||
try:
|
||||
with open("./.lastfetch", "r") as fd:
|
||||
lastfetch = fd.read()
|
||||
logger.debug(f"Last fetch: {lastfetch}")
|
||||
except FileNotFoundError:
|
||||
lastfetch = os.getenv("EPOCH_ID")
|
||||
logger.warning(f"No epoch for last fetch found. Using $EPOCH_ID: {lastfetch}")
|
||||
|
||||
for i in range(5):
|
||||
try:
|
||||
notifications = bot.i_notifications(
|
||||
limit=100,
|
||||
mark_as_read=True,
|
||||
include_types=["reply", "mention"],
|
||||
since_id=lastfetch,
|
||||
)
|
||||
except MisskeyAPIException as e:
|
||||
logger.error("Failed to fetch notifications: %r", e, exc_info=True)
|
||||
retry = random.uniform(0, 2 ** i)
|
||||
logger.warning("Retrying in %.2f seconds...", retry)
|
||||
time.sleep(retry)
|
||||
else:
|
||||
break
|
||||
else:
|
||||
logger.critical("Failed to fetch notifications after 5 retries. Exiting...")
|
||||
sys.exit(1)
|
||||
logger.debug("Fetched another batch of notifications: %r", notifications)
|
||||
for notification in notifications:
|
||||
if notification["note"]["user"].get("isBot", False) is True:
|
||||
logger.debug("Ignoring bot: %r", notification["note"]["user"]["id"])
|
||||
# Ignore bots
|
||||
continue
|
||||
|
||||
logger.info("Replying to post %r", notification["note"]["id"])
|
||||
try:
|
||||
bot.notes_create(
|
||||
text=copy.format(notification, bot),
|
||||
reply_id=notification["note"]["id"],
|
||||
visibility="specified",
|
||||
visible_user_ids=[notification["user"]["id"]],
|
||||
)
|
||||
logger.info("Successfully replied to post %r", notification["note"]["id"])
|
||||
except MisskeyAPIException as e:
|
||||
logger.error("Failed to reply to post %r: %r", notification["note"]["id"], e, exc_info=True)
|
||||
|
||||
try:
|
||||
logger.info("Reacting with the inbox emoji to post %r", notification["note"]["id"])
|
||||
bot.notes_reactions_create(note_id=notification["note"]["id"], reaction="📥")
|
||||
logger.info("Successfully reacted with the inbox emoji to post %r", notification["note"]["id"])
|
||||
except MisskeyAPIException:
|
||||
logger.error("Failed to react with the inbox emoji to post %r", notification["note"]["id"], exc_info=True)
|
||||
with open("./.lastfetch", "w") as fd:
|
||||
fd.write(notification["id"])
|
||||
try:
|
||||
time.sleep(sleep_time)
|
||||
except KeyboardInterrupt:
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
8
copy.txt
Normal file
8
copy.txt
Normal file
|
@ -0,0 +1,8 @@
|
|||
Hello {0[user][name]}!
|
||||
Unfortunately, this account is automated and not checked by a human.
|
||||
If you would like to get in contact with an administrator, please contact @nex@fedi.transgender.ing.
|
||||
|
||||
To make a report, please use your client's report feature.
|
||||
If you are experiencing issues with fedi.transgender.ing, please contact an administrator.
|
||||
|
||||
You can join our Matrix room here: https://matrix.to/#/#fedi:transgender.ing?via=nexy7574.co.uk&via=matrix.org&via=envs.net
|
1
requirements.txt
Normal file
1
requirements.txt
Normal file
|
@ -0,0 +1 @@
|
|||
misskey.py~=4.1
|
2
tox.ini
Normal file
2
tox.ini
Normal file
|
@ -0,0 +1,2 @@
|
|||
[flake8]
|
||||
max-line-length=120
|
Loading…
Reference in a new issue