├── .github ├── dependabot.yml └── workflows │ └── python-ci.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.rst ├── pylama.ini ├── pyproject.toml ├── requirements ├── requirements-dev.txt ├── requirements-test.txt └── requirements.txt ├── setup.py ├── simplebot_mastodon ├── __init__.py ├── mastodon-logo.png ├── migrations.py ├── orm.py └── util.py └── tests └── test_plugin.py /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "pip" # See documentation for possible values 9 | directory: "/requirements" # Location of package manifests 10 | schedule: 11 | interval: "monthly" 12 | -------------------------------------------------------------------------------- /.github/workflows/python-ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | tags: 7 | - 'v*.*.*' 8 | pull_request: 9 | branches: [ master ] 10 | 11 | jobs: 12 | test: 13 | runs-on: ubuntu-latest 14 | strategy: 15 | matrix: 16 | python-version: ['3.10', '3.13'] 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up Python ${{ matrix.python-version }} 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | - name: Install dependencies 24 | run: | 25 | python -m pip install --upgrade pip 26 | python -m pip install '.[dev]' 27 | - name: Check code with black 28 | run: | 29 | black --check . 30 | - name: Lint code 31 | run: | 32 | pylama 33 | - name: Test with pytest 34 | run: | 35 | # pytest 36 | 37 | deploy: 38 | needs: test 39 | runs-on: ubuntu-latest 40 | steps: 41 | - uses: actions/checkout@v2 42 | - uses: actions/setup-python@v2 43 | with: 44 | python-version: '3.x' 45 | - id: check-tag 46 | run: | 47 | if [[ "${{ github.event.ref }}" =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then 48 | echo ::set-output name=match::true 49 | fi 50 | - name: Create PyPI release 51 | uses: casperdcl/deploy-pypi@v2 52 | with: 53 | password: ${{ secrets.PYPI_TOKEN }} 54 | build: true 55 | # only upload if a tag is pushed (otherwise just build & check) 56 | upload: ${{ github.event_name == 'push' && steps.check-tag.outputs.match == 'true' }} 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .cache 3 | .mypy_cache 4 | .pytest_cache 5 | build 6 | dist 7 | .eggs 8 | *.egg-info 9 | */_version.py 10 | 11 | *~ 12 | .#* 13 | *# 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include simplebot_mastodon/mastodon-logo.png 2 | include LICENSE 3 | include README.rst 4 | include CHANGELOG.md -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Mastodon Bridge 2 | =============== 3 | 4 | .. image:: https://img.shields.io/pypi/v/simplebot_mastodon.svg 5 | :target: https://pypi.org/project/simplebot_mastodon 6 | 7 | .. image:: https://img.shields.io/pypi/pyversions/simplebot_mastodon.svg 8 | :target: https://pypi.org/project/simplebot_mastodon 9 | 10 | .. image:: https://pepy.tech/badge/simplebot_mastodon 11 | :target: https://pepy.tech/project/simplebot_mastodon 12 | 13 | .. image:: https://img.shields.io/pypi/l/simplebot_mastodon.svg 14 | :target: https://pypi.org/project/simplebot_mastodon 15 | 16 | .. image:: https://github.com/simplebot-org/simplebot_mastodon/actions/workflows/python-ci.yml/badge.svg 17 | :target: https://github.com/simplebot-org/simplebot_mastodon/actions/workflows/python-ci.yml 18 | 19 | .. image:: https://img.shields.io/badge/code%20style-black-000000.svg 20 | :target: https://github.com/psf/black 21 | 22 | A Mastodon <-> DeltaChat bridge plugin for `SimpleBot`_. 23 | 24 | If this plugin has collisions with commands from other plugins in your bot, you can set a command prefix like ``/masto_`` for all commands:: 25 | 26 | simplebot -a bot@example.com db -s simplebot_mastodon/cmd_prefix masto_ 27 | 28 | Install 29 | ------- 30 | 31 | To install run:: 32 | 33 | pip install simplebot-mastodon 34 | 35 | User Guide 36 | ---------- 37 | 38 | To log in with OAuth, send a message to the bot:: 39 | 40 | /login mastodon.social 41 | 42 | replace "mastodon.social" with your instance, the bot will reply with an URL that you should open to grant access to your account, copy the code you will receive and send it to the bot. 43 | 44 | To log in with your user and password directly(not recommended):: 45 | 46 | /login mastodon.social me@example.com myPassw0rd 47 | 48 | Once you log in, A "Home" and "Notifications" chats will appear, in the Home chat you will receive your Home timeline and any message you send there will be published on Mastodon. In the Notifications chat you will receive all the notifications for your account. 49 | 50 | If someone sends you a direct message in a private 1:1 conversation, it will be shown as a new chat where you can chat in private with that person, to start a private chat with some Mastodon user, send:: 51 | 52 | /dm friend@example.com 53 | 54 | and the chat with "friend@example.com" will pop up. 55 | 56 | To logout from your account:: 57 | 58 | /logout 59 | 60 | For more info and all the available commands(follow, block, mute, etc), send this message to the bot:: 61 | 62 | /help 63 | 64 | 65 | .. _SimpleBot: https://github.com/simplebot-org/simplebot 66 | -------------------------------------------------------------------------------- /pylama.ini: -------------------------------------------------------------------------------- 1 | [pylama] 2 | linters=pyflakes,pylint,isort,mypy 3 | ignore=C0116,C0103,C0301,C0115,R0912,R0914,W0703,R0915,R0903,R0913,R0917 4 | skip=.*,tests/*,build/*,simplebot_*/orm.py,simplebot_*/_version.py 5 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=45", 4 | "setuptools-scm>=6.2", 5 | "wheel", 6 | ] 7 | build-backend = "setuptools.build_meta" 8 | 9 | [tool.setuptools_scm] 10 | write_to = "simplebot_mastodon/_version.py" 11 | 12 | [tool.isort] 13 | profile = "black" 14 | 15 | [tool.mypy] 16 | ignore_missing_imports = "True" 17 | -------------------------------------------------------------------------------- /requirements/requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | -r requirements-test.txt 3 | black==25.1.0 4 | mypy==1.15.0 5 | isort==6.0.1 6 | pylint==3.3.6 7 | pylama==8.4.1 8 | types-requests==2.32.0.20250306 9 | setuptools 10 | -------------------------------------------------------------------------------- /requirements/requirements-test.txt: -------------------------------------------------------------------------------- 1 | pytest==8.3.5 2 | 3 | -------------------------------------------------------------------------------- /requirements/requirements.txt: -------------------------------------------------------------------------------- 1 | simplebot==4.2.0 2 | Mastodon.py==2.0.1 3 | html2text==2024.2.26 4 | beautifulsoup4==4.13.3 5 | requests==2.32.3 6 | pydub==0.25.1 7 | SQLAlchemy==2.0.39 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """Setup module installation.""" 2 | 3 | import os 4 | 5 | from setuptools import find_packages, setup 6 | 7 | 8 | def load_requirements(path: str) -> list: 9 | """Load requirements from the given relative path.""" 10 | with open(path, encoding="utf-8") as file: 11 | requirements = [] 12 | for line in file.read().split("\n"): 13 | if line.startswith("-r"): 14 | dirname = os.path.dirname(path) 15 | filename = line.split(maxsplit=1)[1] 16 | requirements.extend(load_requirements(os.path.join(dirname, filename))) 17 | elif line and not line.startswith("#"): 18 | requirements.append(line.replace("==", ">=")) 19 | return requirements 20 | 21 | 22 | if __name__ == "__main__": 23 | MODULE_NAME = "simplebot_mastodon" 24 | DESC = "Mastodon/DeltaChat bridge." 25 | KEYWORDS = "simplebot plugin deltachat mastodon bridge" 26 | URL = "https://github.com/simplebot-org/simplebot_mastodon" 27 | 28 | with open("README.rst", encoding="utf-8") as fh: 29 | long_description = fh.read() 30 | 31 | setup( 32 | name=MODULE_NAME, 33 | setup_requires=["setuptools_scm"], 34 | use_scm_version={ 35 | "root": ".", 36 | "relative_to": __file__, 37 | "tag_regex": r"^(?Pv)?(?P[^\+]+)(?P.*)?$", 38 | "git_describe_command": "git describe --dirty --tags --long --match v*.*.*", 39 | }, 40 | description=DESC, 41 | long_description=long_description, 42 | long_description_content_type="text/x-rst", 43 | author="adbenitez", 44 | author_email="adb@arcanechat.me", 45 | url=URL, 46 | keywords=KEYWORDS, 47 | license="MPL", 48 | classifiers=[ 49 | "Development Status :: 4 - Beta", 50 | "Environment :: Plugins", 51 | "Programming Language :: Python :: 3", 52 | "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", 53 | "Operating System :: OS Independent", 54 | "Topic :: Utilities", 55 | ], 56 | python_requires=">=3.10", 57 | zip_safe=False, 58 | include_package_data=True, 59 | packages=find_packages(), 60 | install_requires=load_requirements("requirements/requirements.txt"), 61 | extras_require={ 62 | "test": load_requirements("requirements/requirements-test.txt"), 63 | "dev": load_requirements("requirements/requirements-dev.txt"), 64 | }, 65 | entry_points={ 66 | "simplebot.plugins": f"{MODULE_NAME} = {MODULE_NAME}", 67 | }, 68 | ) 69 | -------------------------------------------------------------------------------- /simplebot_mastodon/__init__.py: -------------------------------------------------------------------------------- 1 | """hooks, filters and commands""" 2 | 3 | import os 4 | import re 5 | from threading import Thread 6 | from typing import List 7 | 8 | import mastodon 9 | import simplebot 10 | from deltachat import Chat, Contact, Message, account_hookimpl 11 | from deltachat.events import FFIEvent 12 | from simplebot.bot import DeltaBot, Replies 13 | 14 | from .migrations import run_migrations 15 | from .orm import Account, DmChat, OAuth, init, session_scope 16 | from .util import ( 17 | TOOT_SEP, 18 | Visibility, 19 | account_action, 20 | download_file, 21 | get_account_from_msg, 22 | get_client, 23 | get_database_path, 24 | get_mastodon, 25 | get_mastodon_from_msg, 26 | get_profile, 27 | get_user, 28 | getdefault, 29 | listen_to_mastodon, 30 | normalize_url, 31 | send_toot, 32 | toots2texts, 33 | ) 34 | 35 | MASTODON_LOGO = os.path.join(os.path.dirname(__file__), "mastodon-logo.png") 36 | STAR_REACTIONS = ["⭐", "👍", "❤️"] 37 | 38 | 39 | class AccountPlugin: 40 | def __init__(self, bot: DeltaBot) -> None: 41 | self.bot = bot 42 | 43 | @account_hookimpl 44 | def ac_process_ffi_event(self, ffi_event: FFIEvent) -> None: 45 | if ffi_event.name == "DC_EVENT_REACTIONS_CHANGED": 46 | msg = self.bot.account.get_message_by_id(ffi_event.data2) 47 | 48 | toot_id = re.findall(r"/star_(\d+)", msg.text) 49 | if len(toot_id) != 1: 50 | return 51 | toot_id = toot_id[0] 52 | 53 | star = False 54 | reactions = msg.get_reactions() 55 | for contact in reactions.get_contacts(): 56 | for reaction in reactions.get_by_contact(contact).split(): 57 | if reaction in STAR_REACTIONS: 58 | star = True 59 | break 60 | 61 | masto = get_mastodon_from_msg(msg) 62 | if masto: 63 | if star: 64 | masto.status_favourite(toot_id) 65 | else: 66 | masto.status_unfavourite(toot_id) 67 | 68 | 69 | @simplebot.hookimpl 70 | def deltabot_init(bot: DeltaBot) -> None: 71 | bot.account.add_account_plugin(AccountPlugin(bot)) 72 | 73 | getdefault(bot, "delay", "30") 74 | getdefault(bot, "max_users", "-1") 75 | getdefault(bot, "max_users_instance", "-1") 76 | pref = getdefault(bot, "cmd_prefix", "") 77 | 78 | bot.commands.register(func=logout_cmd, name=f"/{pref}logout") 79 | bot.commands.register(func=reply_cmd, name=f"/{pref}reply", hidden=True) 80 | bot.commands.register(func=star_cmd, name=f"/{pref}star", hidden=True) 81 | bot.commands.register(func=boost_cmd, name=f"/{pref}boost", hidden=True) 82 | bot.commands.register(func=open_cmd, name=f"/{pref}open", hidden=True) 83 | bot.commands.register(func=avatar_cmd, name=f"/{pref}avatar") 84 | bot.commands.register(func=local_cmd, name=f"/{pref}local") 85 | bot.commands.register(func=public_cmd, name=f"/{pref}public") 86 | 87 | desc = f"Login on Mastodon.\n\nExample:\n/{pref}login mastodon.social\n\nTo login without OAuth:\n/{pref}login mastodon.social me@example.com myPassw0rd" 88 | bot.commands.register(func=login_cmd, name=f"/{pref}login", help=desc) 89 | 90 | desc = f"Update your Mastodon biography.\n\nExample:\n/{pref}bio I love Delta Chat" 91 | bot.commands.register(func=bio_cmd, name=f"/{pref}bio", help=desc) 92 | 93 | desc = f"Start a private chat with the given Mastodon user.\n\nExample:\n/{pref}dm user@mastodon.social" 94 | bot.commands.register(func=dm_cmd, name=f"/{pref}dm", help=desc) 95 | 96 | desc = f"Follow the user with the given account name or id.\n\nExample:\n/{pref}follow user@mastodon.social" 97 | bot.commands.register(func=follow_cmd, name=f"/{pref}follow", help=desc) 98 | 99 | desc = f"Unfollow the user with the given account name or id.\n\nExample:\n/{pref}unfollow user@mastodon.social" 100 | bot.commands.register(func=unfollow_cmd, name=f"/{pref}unfollow", help=desc) 101 | 102 | desc = f"Mute the user with the given account name or id. If sent in the Home chat it will mute the Home timeline.\n\nExample:\n/{pref}mute user@mastodon.social\n\nTo mute Home timeline:\n/{pref}mute" 103 | bot.commands.register(func=mute_cmd, name=f"/{pref}mute", help=desc) 104 | 105 | desc = f"Unmute the user with the given account name or id. If sent in the Home chat it will unmute the Home timeline.\n\nExample:\n/{pref}unmute user@mastodon.social\n\nTo unmute Home timeline:\n/{pref}unmute" 106 | bot.commands.register(func=unmute_cmd, name=f"/{pref}unmute", help=desc) 107 | 108 | desc = f"Block the user with the given account name or id.\n\nExample:\n/{pref}block user@mastodon.social" 109 | bot.commands.register(func=block_cmd, name=f"/{pref}block", help=desc) 110 | 111 | desc = f"Unblock the user with the given account name or id.\n\nExample:\n/{pref}unblock user@mastodon.social" 112 | bot.commands.register(func=unblock_cmd, name=f"/{pref}unblock", help=desc) 113 | 114 | desc = f"See the profile of the given user.\n\nExample:\n/{pref}profile user@mastodon.social" 115 | bot.commands.register(func=profile_cmd, name=f"/{pref}profile", help=desc) 116 | 117 | desc = f"Get latest entries with the given hashtags.\n\nExamples:\n/{pref}tag deltachat\n/{pref}tag mastocat" 118 | bot.commands.register(func=tag_cmd, name=f"/{pref}tag", help=desc) 119 | 120 | desc = f"Search for users and hashtags matching the given text.\n\nExamples:\n/{pref}search deltachat\n/{pref}search mastocat" 121 | bot.commands.register(func=search_cmd, name=f"/{pref}search", help=desc) 122 | 123 | 124 | @simplebot.hookimpl 125 | def deltabot_start(bot: DeltaBot) -> None: 126 | run_migrations(bot) 127 | init(f"sqlite:///{get_database_path(bot)}") 128 | Thread(target=listen_to_mastodon, args=(bot,), daemon=True).start() 129 | 130 | 131 | @simplebot.hookimpl 132 | def deltabot_member_removed( 133 | bot: DeltaBot, chat: Chat, contact: Contact, replies: Replies 134 | ) -> None: 135 | if bot.self_contact != contact and len(chat.get_contacts()) > 1: 136 | return 137 | 138 | url = "" 139 | addr = "" 140 | chats: List[int] = [] 141 | with session_scope() as session: 142 | acc = ( 143 | session.query(Account) 144 | .filter((Account.home == chat.id) | (Account.notifications == chat.id)) 145 | .first() 146 | ) 147 | if acc: 148 | url = acc.url 149 | addr = acc.addr 150 | chats.extend(dmchat.chat_id for dmchat in acc.dm_chats) 151 | chats.append(acc.home) 152 | chats.append(acc.notifications) 153 | session.delete(acc) 154 | else: 155 | dmchat = session.query(DmChat).filter_by(chat_id=chat.id).first() 156 | if dmchat: 157 | chats.append(chat.id) 158 | session.delete(dmchat) 159 | 160 | for chat_id in chats: 161 | try: 162 | bot.get_chat(chat_id).remove_contact(bot.self_contact) 163 | except ValueError: 164 | pass 165 | 166 | if url: 167 | replies.add(text=f"✔️ You logged out from: {url}", chat=bot.get_chat(addr)) 168 | 169 | 170 | @simplebot.filter 171 | def filter_messages(bot: DeltaBot, message: Message, replies: Replies) -> None: 172 | """Once you log in with your Mastodon credentials, two chats will be created for you: 173 | 174 | • The Home chat is where you will receive your Home timeline and any message you send in that chat will be published on Mastodon. 175 | • The Notifications chat is where you will receive your Mastodon notifications. 176 | 177 | When a Mastodon user writes a private/direct message to you, a chat will be created for your private conversation with that user. 178 | """ 179 | if not message.chat.is_multiuser(): 180 | addr = message.get_sender_contact().addr 181 | with session_scope() as session: 182 | auth = session.query(OAuth).filter_by(addr=addr).first() 183 | if not auth: 184 | replies.add( 185 | text="❌ To publish messages you must send them in your Home chat.", 186 | quote=message, 187 | ) 188 | return 189 | url, user, client_id, client_secret = ( 190 | auth.url, 191 | auth.user, 192 | auth.client_id, 193 | auth.client_secret, 194 | ) 195 | m = get_mastodon(url, client_id=client_id, client_secret=client_secret) 196 | try: 197 | m.log_in(code=message.text.strip()) 198 | _login(addr, user, m, bot, replies) 199 | with session_scope() as session: 200 | session.delete(session.query(OAuth).filter_by(addr=addr).first()) 201 | except Exception: # noqa 202 | text = "❌ Authentication failed, generate another authorization code and send it here" 203 | replies.add(text=text, quote=message) 204 | return 205 | 206 | api_url: str = "" 207 | token = "" 208 | args: tuple = () 209 | with session_scope() as session: 210 | acc = ( 211 | session.query(Account) 212 | .filter( 213 | (Account.home == message.chat.id) 214 | | (Account.notifications == message.chat.id) 215 | ) 216 | .first() 217 | ) 218 | if acc: 219 | if acc.home == message.chat.id: 220 | api_url = acc.url 221 | token = acc.token 222 | args = (message.text, message.filename) 223 | elif len(message.chat.get_contacts()) <= 2: 224 | # only send directly if not in team usage 225 | dmchat = session.query(DmChat).filter_by(chat_id=message.chat.id).first() 226 | if dmchat: 227 | api_url = dmchat.account.url 228 | token = dmchat.account.token 229 | args = ( 230 | f"@{dmchat.contact} {message.text}", 231 | message.filename, 232 | Visibility.DIRECT, 233 | ) 234 | 235 | if api_url: 236 | send_toot(get_mastodon(api_url, token), *args) 237 | 238 | 239 | def login_cmd(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None: 240 | args = payload.split(maxsplit=2) 241 | if len(args) == 1: 242 | api_url, email, passwd = args[0], None, None 243 | else: 244 | if len(args) != 3: 245 | replies.add(text="❌ Wrong usage", quote=message) 246 | return 247 | api_url, email, passwd = args 248 | api_url = normalize_url(api_url) 249 | addr = message.get_sender_contact().addr 250 | 251 | user = "" 252 | with session_scope() as session: 253 | acc = session.query(Account).filter_by(addr=addr).first() 254 | if acc: 255 | if acc.url != api_url: 256 | replies.add(text="❌ You are already logged in.") 257 | return 258 | user = acc.user 259 | else: 260 | maximum = int(getdefault(bot, "max_users")) 261 | if 0 <= maximum <= session.query(Account).count(): 262 | replies.add(text="❌ No more users allowed in this bot.") 263 | return 264 | maximum = int(getdefault(bot, "max_users_instance")) 265 | if 0 <= maximum <= session.query(Account).filter_by(url=api_url).count(): 266 | replies.add(text=f"❌ No more users from {api_url} allowed in this bot") 267 | return 268 | 269 | client_id, client_secret = get_client(session, api_url) 270 | 271 | m = get_mastodon(api_url, client_id=client_id, client_secret=client_secret) 272 | 273 | if email: 274 | m.log_in(email, passwd) 275 | _login(addr, user, m, bot, replies) 276 | else: 277 | if client_id is None: 278 | replies.add( 279 | text="❌ Server doesn't seem to support OAuth.", 280 | quote=message, 281 | ) 282 | return 283 | with session_scope() as session: 284 | auth = session.query(OAuth).filter_by(addr=addr).first() 285 | if not auth: 286 | session.add( 287 | OAuth( 288 | addr=addr, 289 | url=api_url, 290 | user=user, 291 | client_id=client_id, 292 | client_secret=client_secret, 293 | ) 294 | ) 295 | else: 296 | auth.url = api_url 297 | auth.client_id = client_id 298 | auth.client_secret = client_secret 299 | auth.user = user 300 | auth_url = m.auth_request_url() 301 | text = ( 302 | f"To grant access to your account, open this URL:\n\n{auth_url}\n\n" 303 | "You will get an authorization code, copy it and send it here" 304 | ) 305 | replies.add(text=text, quote=message) 306 | 307 | 308 | def _login( 309 | addr: str, user: str, masto: mastodon.Mastodon, bot: DeltaBot, replies: Replies 310 | ) -> None: 311 | uname = masto.me().acct.lower() 312 | 313 | if user: 314 | if user == uname: 315 | with session_scope() as session: 316 | acc = session.query(Account).filter_by(addr=addr).first() 317 | acc.token = masto.access_token 318 | replies.add(text="✔️ You refreshed your credentials.") 319 | else: 320 | replies.add(text="❌ You are already logged in.") 321 | return 322 | 323 | n = masto.notifications(limit=1) 324 | last_notif = n[0].id if n else None 325 | n = masto.timeline_home(limit=1) 326 | last_home = n[0].id if n else None 327 | 328 | api_url = masto.api_base_url 329 | url = api_url.split("://", maxsplit=1)[-1] 330 | hgroup = bot.create_group(f"Home ({url})", [addr]) 331 | ngroup = bot.create_group(f"Notifications ({url})", [addr]) 332 | 333 | with session_scope() as session: 334 | session.add( 335 | Account( 336 | addr=addr, 337 | user=uname, 338 | url=api_url, 339 | token=masto.access_token, 340 | home=hgroup.id, 341 | notifications=ngroup.id, 342 | last_home=last_home, 343 | last_notif=last_notif, 344 | ) 345 | ) 346 | 347 | hgroup.set_profile_image(MASTODON_LOGO) 348 | pref = getdefault(bot, "cmd_prefix", "") 349 | replies.add( 350 | text=f"ℹ️ Messages sent here will be published in @{uname}@{url}\n\nIf your Home timeline is too noisy and you would like to disable incoming toots, send /{pref}mute here.", 351 | chat=hgroup, 352 | ) 353 | 354 | ngroup.set_profile_image(MASTODON_LOGO) 355 | replies.add( 356 | text=f"ℹ️ Here you will receive notifications for @{uname}@{url}", chat=ngroup 357 | ) 358 | 359 | 360 | def logout_cmd(bot: DeltaBot, message: Message, replies: Replies) -> None: 361 | """Logout from Mastodon.""" 362 | addr = message.get_sender_contact().addr 363 | chats: List[int] = [] 364 | with session_scope() as session: 365 | acc = session.query(Account).filter_by(addr=addr).first() 366 | if acc: 367 | text = f"✔️ You logged out from: {acc.url}" 368 | chats.extend(dmchat.chat_id for dmchat in acc.dm_chats) 369 | chats.append(acc.home) 370 | chats.append(acc.notifications) 371 | session.delete(acc) 372 | else: 373 | text = "❌ You are not logged in" 374 | 375 | for chat_id in chats: 376 | try: 377 | bot.get_chat(chat_id).remove_contact(bot.self_contact) 378 | except ValueError: 379 | pass 380 | replies.add(text=text, chat=bot.get_chat(addr)) 381 | 382 | 383 | def bio_cmd(payload: str, message: Message, replies: Replies) -> None: 384 | if not payload: 385 | replies.add(text="❌ Wrong usage", quote=message) 386 | return 387 | 388 | masto = get_mastodon_from_msg(message) 389 | if masto: 390 | try: 391 | masto.account_update_credentials(note=payload) 392 | text = "✔️ Biography updated" 393 | except mastodon.MastodonAPIError as err: 394 | text = f"❌ ERROR: {err.args[-1]}" 395 | else: 396 | text = "❌ You are not logged in" 397 | replies.add(text=text, quote=message) 398 | 399 | 400 | def avatar_cmd(message: Message, replies: Replies) -> None: 401 | """Update your Mastodon avatar. 402 | 403 | In addition to this command, you must attach the avatar image you want to set. 404 | """ 405 | if not message.filename: 406 | replies.add( 407 | text="❌ You must send an avatar attached to your message", quote=message 408 | ) 409 | return 410 | 411 | masto = get_mastodon_from_msg(message) 412 | if masto: 413 | try: 414 | masto.account_update_credentials(avatar=message.filename) 415 | text = "✔️ Avatar updated" 416 | except mastodon.MastodonAPIError: 417 | text = "❌ Failed to update avatar" 418 | else: 419 | text = "❌ You are not logged in" 420 | replies.add(text=text, quote=message) 421 | 422 | 423 | def dm_cmd(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None: 424 | if not payload: 425 | replies.add(text="❌ Wrong usage", quote=message) 426 | return 427 | 428 | masto = get_mastodon_from_msg(message) 429 | if masto: 430 | username = payload.lstrip("@").lower() 431 | user = get_user(masto, username) 432 | if not user: 433 | replies.add(text=f"❌ Account not found: {username}", quote=message) 434 | return 435 | 436 | with session_scope() as session: 437 | acc = get_account_from_msg(message, session) 438 | assert acc 439 | dmchat = ( 440 | session.query(DmChat) 441 | .filter_by(acc_addr=acc.addr, contact=user.acct) 442 | .first() 443 | ) 444 | if dmchat: 445 | chat = bot.get_chat(dmchat.chat_id) 446 | replies.add( 447 | text="❌ Chat already exists, send messages here", chat=chat 448 | ) 449 | return 450 | chat = bot.create_group( 451 | user.acct, bot.get_chat(acc.notifications).get_contacts() 452 | ) 453 | session.add(DmChat(chat_id=chat.id, contact=user.acct, acc_addr=acc.addr)) 454 | 455 | try: 456 | path = download_file(bot, user.avatar_static, ".jpg") 457 | chat.set_profile_image(path) 458 | except ValueError as err: 459 | bot.logger.exception(err) 460 | os.remove(path) 461 | except Exception as err: 462 | bot.logger.exception(err) 463 | replies.add(text=f"ℹ️ Private chat with: {user.acct}", chat=chat) 464 | else: 465 | replies.add(text="❌ You are not logged in", quote=message) 466 | 467 | 468 | def reply_cmd(payload: str, message: Message, replies: Replies) -> None: 469 | """Reply to a toot with the given id.""" 470 | args = payload.split(maxsplit=1) 471 | if len(args) != 2 and not (args and message.filename): 472 | replies.add(text="❌ Wrong usage", quote=message) 473 | return 474 | 475 | toot_id = args.pop(0) 476 | text = args.pop(0) if args else "" 477 | 478 | masto = get_mastodon_from_msg(message) 479 | if masto: 480 | send_toot(masto, text=text, filename=message.filename, in_reply_to=toot_id) 481 | else: 482 | replies.add(text="❌ You are not logged in", quote=message) 483 | 484 | 485 | def star_cmd(payload: str, message: Message, replies: Replies) -> None: 486 | """Mark as favourite the toot with the given id.""" 487 | if not payload: 488 | replies.add(text="❌ Wrong usage", quote=message) 489 | else: 490 | masto = get_mastodon_from_msg(message) 491 | if masto: 492 | masto.status_favourite(payload) 493 | else: 494 | replies.add(text="❌ You are not logged in", quote=message) 495 | 496 | 497 | def boost_cmd(payload: str, message: Message, replies: Replies) -> None: 498 | """Boost the toot with the given id.""" 499 | if not payload: 500 | replies.add(text="❌ Wrong usage", quote=message) 501 | else: 502 | masto = get_mastodon_from_msg(message) 503 | if masto: 504 | masto.status_reblog(payload) 505 | else: 506 | replies.add(text="❌ You are not logged in", quote=message) 507 | 508 | 509 | def open_cmd(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None: 510 | """Open the thread of the toot with the given id.""" 511 | if not payload: 512 | replies.add(text="❌ Wrong usage", quote=message) 513 | else: 514 | masto = get_mastodon_from_msg(message) 515 | if masto: 516 | context = masto.status_context(payload) 517 | toots = ( 518 | context["ancestors"] + [masto.status(payload)] + context["descendants"] 519 | ) 520 | replies.add( 521 | text=( 522 | TOOT_SEP.join(toots2texts(bot, toots)) 523 | if toots 524 | else "❌ Nothing found" 525 | ), 526 | quote=message, 527 | ) 528 | else: 529 | replies.add(text="❌ You are not logged in", quote=message) 530 | 531 | 532 | def follow_cmd(payload: str, message: Message, replies: Replies) -> None: 533 | replies.add( 534 | text=account_action("account_follow", payload, message) or "✔️ User followed", 535 | quote=message, 536 | ) 537 | 538 | 539 | def unfollow_cmd(payload: str, message: Message, replies: Replies) -> None: 540 | replies.add( 541 | text=account_action("account_unfollow", payload, message) 542 | or "✔️ User unfollowed", 543 | quote=message, 544 | ) 545 | 546 | 547 | def mute_cmd(payload: str, message: Message, replies: Replies) -> None: 548 | if payload: 549 | replies.add( 550 | text=account_action("account_mute", payload, message) or "✔️ User muted", 551 | quote=message, 552 | ) 553 | return 554 | 555 | # check if the message was sent in the Home or Notifications chat 556 | with session_scope() as session: 557 | acc = session.query(Account).filter_by(home=message.chat.id).first() 558 | if acc: 559 | acc.muted_home = True 560 | acc.last_home = None 561 | replies.add( 562 | text="✔️ Home timeline muted", 563 | quote=message, 564 | ) 565 | return 566 | 567 | acc = session.query(Account).filter_by(notifications=message.chat.id).first() 568 | if acc: 569 | acc.muted_notif = True 570 | replies.add( 571 | text="✔️ Notifications timeline muted: follows, favorites and boosts will not be notified", 572 | quote=message, 573 | ) 574 | else: 575 | replies.add( 576 | text="❌ Wrong usage, you must send that command in the Home or Notifications chat to mute them", 577 | quote=message, 578 | ) 579 | 580 | 581 | def unmute_cmd(payload: str, message: Message, replies: Replies) -> None: 582 | if payload: 583 | replies.add( 584 | text=account_action("account_unmute", payload, message) or "✔️ User unmuted", 585 | quote=message, 586 | ) 587 | return 588 | 589 | # check if the message was sent in the Home or Notifications chat 590 | with session_scope() as session: 591 | acc = session.query(Account).filter_by(home=message.chat.id).first() 592 | if acc: 593 | acc.muted_home = False 594 | toots = get_mastodon(acc.url, acc.token).timeline_home(limit=1) 595 | acc.last_home = toots[0].id if toots else None 596 | replies.add( 597 | text="✔️ Home timeline unmuted", 598 | quote=message, 599 | ) 600 | return 601 | 602 | acc = session.query(Account).filter_by(notifications=message.chat.id).first() 603 | if acc: 604 | acc.muted_notif = False 605 | replies.add(text="✔️ Notifications timeline unmuted", quote=message) 606 | else: 607 | replies.add( 608 | text="❌ Wrong usage, you must send that command in the Home or Notifications chat to unmute them", 609 | quote=message, 610 | ) 611 | 612 | 613 | def block_cmd(payload: str, message: Message, replies: Replies) -> None: 614 | replies.add( 615 | text=account_action("account_block", payload, message) or "✔️ User blocked", 616 | quote=message, 617 | ) 618 | 619 | 620 | def unblock_cmd(payload: str, message: Message, replies: Replies) -> None: 621 | replies.add( 622 | text=account_action("account_unblock", payload, message) or "✔️ User unblocked", 623 | quote=message, 624 | ) 625 | 626 | 627 | def profile_cmd( 628 | bot: DeltaBot, payload: str, message: Message, replies: Replies 629 | ) -> None: 630 | masto = get_mastodon_from_msg(message) 631 | if masto: 632 | text = get_profile(bot, masto, payload) 633 | else: 634 | text = "❌ You are not logged in" 635 | replies.add(text=text, quote=message) 636 | 637 | 638 | def local_cmd(bot: DeltaBot, message: Message, replies: Replies) -> None: 639 | """Get latest entries from the local timeline.""" 640 | masto = get_mastodon_from_msg(message) 641 | if masto: 642 | text = ( 643 | TOOT_SEP.join(toots2texts(bot, reversed(masto.timeline_local()))) 644 | or "❌ Nothing found" 645 | ) 646 | else: 647 | text = "❌ You are not logged in" 648 | replies.add(text=text, quote=message) 649 | 650 | 651 | def public_cmd(bot: DeltaBot, message: Message, replies: Replies) -> None: 652 | """Get latest entries from the public timeline.""" 653 | masto = get_mastodon_from_msg(message) 654 | if masto: 655 | text = ( 656 | TOOT_SEP.join(toots2texts(bot, reversed(masto.timeline_public()))) 657 | or "❌ Nothing found" 658 | ) 659 | else: 660 | text = "❌ You are not logged in" 661 | replies.add(text=text, quote=message) 662 | 663 | 664 | def tag_cmd(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None: 665 | if not payload: 666 | replies.add(text="❌ Wrong usage", quote=message) 667 | return 668 | 669 | tag = payload.lstrip("#") 670 | masto = get_mastodon_from_msg(message) 671 | if masto: 672 | text = ( 673 | TOOT_SEP.join(toots2texts(bot, reversed(masto.timeline_hashtag(tag)))) 674 | or "❌ Nothing found" 675 | ) 676 | else: 677 | text = "❌ You are not logged in" 678 | replies.add(text=text, quote=message) 679 | 680 | 681 | def search_cmd(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None: 682 | if not payload: 683 | replies.add(text="❌ Wrong usage", quote=message) 684 | return 685 | 686 | masto = get_mastodon_from_msg(message) 687 | if masto: 688 | res = masto.search(payload) 689 | prefix = getdefault(bot, "cmd_prefix", "") 690 | text = "" 691 | if res["accounts"]: 692 | text += "👤 Accounts:" 693 | for a in res["accounts"]: 694 | text += f"\n@{a.acct} /{prefix}profile_{a.id}" 695 | text += "\n\n" 696 | if res["hashtags"]: 697 | text += "#️⃣ Hashtags:" 698 | for tag in res["hashtags"]: 699 | text += f"\n#{tag.name} /{prefix}tag_{tag.name}" 700 | if not text: 701 | text = "❌ Nothing found" 702 | else: 703 | text = "❌ You are not logged in" 704 | replies.add(text=text, quote=message) 705 | -------------------------------------------------------------------------------- /simplebot_mastodon/mastodon-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simplebot-org/simplebot_mastodon/98c4c0e70a6d638c31b7de4ec3f7c3bf52e40de0/simplebot_mastodon/mastodon-logo.png -------------------------------------------------------------------------------- /simplebot_mastodon/migrations.py: -------------------------------------------------------------------------------- 1 | """Database migrations""" 2 | 3 | import os 4 | import sqlite3 5 | 6 | from simplebot.bot import DeltaBot 7 | 8 | from .util import get_database_path 9 | 10 | DATABASE_VERSION = 2 11 | 12 | 13 | def get_db_version(database: sqlite3.Connection) -> int: 14 | with database: 15 | database.execute( 16 | """CREATE TABLE IF NOT EXISTS "database" ( 17 | "id" INTEGER NOT NULL, 18 | "version" INTEGER NOT NULL, 19 | PRIMARY KEY("id") 20 | )""" 21 | ) 22 | row = database.execute("SELECT version FROM database").fetchone() 23 | return row["version"] if row else 0 24 | 25 | 26 | def run_migrations(bot: DeltaBot) -> None: 27 | path = get_database_path(bot) 28 | if not os.path.exists(path): 29 | bot.logger.debug("Database doesn't exists, skipping migrations") 30 | return 31 | 32 | database = sqlite3.connect(path) 33 | database.row_factory = sqlite3.Row 34 | try: 35 | version = get_db_version(database) 36 | bot.logger.debug(f"Current database version: v{version}") 37 | for i in range(version + 1, DATABASE_VERSION + 1): 38 | migration = globals().get(f"migrate{i}") 39 | assert migration 40 | bot.logger.info(f"Migrating database: v{i}") 41 | with database: 42 | database.execute("REPLACE INTO database VALUES (?,?)", (1, i)) 43 | migration(database) 44 | finally: 45 | database.close() 46 | 47 | 48 | def migrate1(database: sqlite3.Connection) -> None: 49 | try: 50 | database.execute("ALTER TABLE account ADD COLUMN muted_home BOOLEAN") 51 | except Exception as ex: 52 | # ignore to avoid crash caused by accidental empty database table 53 | print(f"WARNING: ignoring exception: {ex}") 54 | 55 | 56 | def migrate2(database: sqlite3.Connection) -> None: 57 | database.execute("ALTER TABLE account ADD COLUMN muted_notif BOOLEAN") 58 | -------------------------------------------------------------------------------- /simplebot_mastodon/orm.py: -------------------------------------------------------------------------------- 1 | from contextlib import contextmanager 2 | from threading import Lock 3 | 4 | from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, create_engine 5 | from sqlalchemy.ext.declarative import declarative_base, declared_attr 6 | from sqlalchemy.orm import relationship, sessionmaker 7 | 8 | 9 | class Base: 10 | @declared_attr 11 | def __tablename__(self): 12 | return self.__name__.lower() 13 | 14 | 15 | Base = declarative_base(cls=Base) 16 | _Session = sessionmaker() 17 | _lock = Lock() 18 | 19 | 20 | class Account(Base): 21 | addr = Column(String(1000), primary_key=True) 22 | user = Column(String(1000), nullable=False) 23 | url = Column(String(1000), nullable=False) 24 | token = Column(String(1000), nullable=False) 25 | home = Column(Integer, nullable=False) 26 | notifications = Column(Integer, nullable=False) 27 | last_home = Column(String(1000)) 28 | last_notif = Column(String(1000)) 29 | muted_home = Column(Boolean) 30 | muted_notif = Column(Boolean) 31 | 32 | dm_chats = relationship( 33 | "DmChat", backref="account", cascade="all, delete, delete-orphan" 34 | ) 35 | 36 | 37 | class DmChat(Base): 38 | chat_id = Column(Integer, primary_key=True) 39 | contact = Column(String(1000), nullable=False) 40 | acc_addr = Column(String(1000), ForeignKey("account.addr"), nullable=False) 41 | 42 | 43 | class OAuth(Base): 44 | addr = Column(String(1000), primary_key=True) 45 | url = Column(String(1000), nullable=False) 46 | user = Column(String(1000)) 47 | client_id = Column(String(1000), nullable=False) 48 | client_secret = Column(String(1000), nullable=False) 49 | 50 | 51 | class Client(Base): 52 | url = Column(String(1000), primary_key=True) 53 | id = Column(String(1000)) 54 | secret = Column(String(1000)) 55 | 56 | 57 | @contextmanager 58 | def session_scope(): 59 | """Provide a transactional scope around a series of operations.""" 60 | with _lock: 61 | session = _Session() 62 | try: 63 | yield session 64 | session.commit() 65 | except Exception: 66 | session.rollback() 67 | raise 68 | finally: 69 | session.close() 70 | 71 | 72 | def init(path: str, debug: bool = False) -> None: 73 | """Initialize engine.""" 74 | engine = create_engine(path, echo=debug) 75 | Base.metadata.create_all(engine) 76 | _Session.configure(bind=engine) 77 | -------------------------------------------------------------------------------- /simplebot_mastodon/util.py: -------------------------------------------------------------------------------- 1 | """Utilities""" 2 | 3 | import functools 4 | import mimetypes 5 | import os 6 | import re 7 | import time 8 | from enum import Enum 9 | from tempfile import NamedTemporaryFile 10 | from typing import Any, Dict, Generator, Iterable, List, Optional 11 | 12 | import requests 13 | from bs4 import BeautifulSoup 14 | from deltachat import Chat, Message 15 | from html2text import html2text 16 | from mastodon import ( 17 | AttribAccessDict, 18 | Mastodon, 19 | MastodonNetworkError, 20 | MastodonServerError, 21 | MastodonUnauthorizedError, 22 | ) 23 | from pydub import AudioSegment 24 | from simplebot.bot import DeltaBot, Replies 25 | 26 | from .orm import Account, Client, DmChat, session_scope 27 | 28 | SPAM = [ 29 | "/fediversechick/", 30 | "https://discord.gg/83CnebyzXh", 31 | "https://matrix.to/#/#nicoles_place:matrix.org", 32 | ] 33 | MUTED_NOTIFICATIONS = ("reblog", "favourite", "follow") 34 | TOOT_SEP = "\n\n―――――――――――――――\n\n" 35 | STRFORMAT = "%Y-%m-%d %H:%M" 36 | _scope = __name__.split(".", maxsplit=1)[0] 37 | web = requests.Session() 38 | web.request = functools.partial(web.request, timeout=10) # type: ignore 39 | 40 | 41 | class Visibility(str, Enum): 42 | DIRECT = "direct" # visible only to mentioned users 43 | PRIVATE = "private" # visible only to followers 44 | UNLISTED = "unlisted" # public but not appear on the public timeline 45 | PUBLIC = "public" # post will be public 46 | 47 | 48 | v2emoji = { 49 | Visibility.DIRECT: "✉", 50 | Visibility.PRIVATE: "🔒", 51 | Visibility.UNLISTED: "🔓", 52 | Visibility.PUBLIC: "🌎", 53 | } 54 | 55 | 56 | def toots2texts(bot: DeltaBot, toots: Iterable) -> Generator: 57 | prefix = getdefault(bot, "cmd_prefix", "") 58 | for toot in toots: 59 | reply = toot2reply(prefix, toot) 60 | text = reply.get("text", "") 61 | if reply.get("filename"): 62 | if not text.startswith("http"): 63 | text = "\n" + text 64 | text = reply["filename"] + "\n" + text 65 | sender = reply.get("sender", "") 66 | if sender: 67 | text = f"{sender}:\n{text}" 68 | if text: 69 | yield text 70 | 71 | 72 | def toots2replies(bot: DeltaBot, toots: Iterable) -> Generator: 73 | prefix = getdefault(bot, "cmd_prefix", "") 74 | for toot in toots: 75 | reply = toot2reply(prefix, toot) 76 | if reply.get("filename"): 77 | try: 78 | reply["filename"] = download_file(bot, reply["filename"]) 79 | except Exception as ex: 80 | bot.logger.exception(ex) 81 | text = reply.get("text", "") 82 | if not text.startswith("http"): 83 | text = "\n" + text 84 | reply["text"] = reply["filename"] + "\n" + text 85 | del reply["filename"] 86 | if reply: 87 | yield reply 88 | 89 | 90 | def toot2reply(prefix: str, toot: AttribAccessDict) -> dict: 91 | text = "" 92 | reply = {} 93 | if toot.reblog: 94 | reply["sender"] = _get_name(toot.reblog.account) 95 | text += f"🔁 {_get_name(toot.account)}\n\n" 96 | toot = toot.reblog 97 | else: 98 | reply["sender"] = _get_name(toot.account) 99 | 100 | if toot.media_attachments: 101 | reply["filename"] = toot.media_attachments.pop(0).url 102 | text += "\n".join(media.url for media in toot.media_attachments) + "\n\n" 103 | 104 | soup = BeautifulSoup(toot.content, "html.parser") 105 | if toot.mentions: 106 | accts = {e.url: "@" + e.acct for e in toot.mentions} 107 | for anchor in soup("a", class_="u-url"): 108 | name = accts.get(anchor["href"], "") 109 | if name: 110 | anchor.string = name 111 | for linebreak in soup("br"): 112 | linebreak.replace_with("\n") 113 | for paragraph in soup("p"): 114 | paragraph.replace_with(paragraph.get_text() + "\n\n") 115 | text += soup.get_text() 116 | 117 | text += f"\n\n[{v2emoji[toot.visibility]} {toot.created_at.strftime(STRFORMAT)}]({toot.url})\n" 118 | text += f"↩️ /{prefix}reply_{toot.id}\n" 119 | text += f"⭐ /{prefix}star_{toot.id}\n" 120 | if toot.visibility in (Visibility.PUBLIC, Visibility.UNLISTED): 121 | text += f"🔁 /{prefix}boost_{toot.id}\n" 122 | text += f"⏫ /{prefix}open_{toot.id}\n" 123 | text += f"👤 /{prefix}profile_{toot.account.id}\n" 124 | 125 | reply["text"] = text 126 | return reply 127 | 128 | 129 | def notif2replies(toots: Iterable) -> Generator: 130 | for toot in toots: 131 | reply = notif2reply(toot) 132 | if reply: 133 | yield reply 134 | 135 | 136 | def notif2reply(toots: list[AttribAccessDict]) -> dict: 137 | toot_type = toots[0].type 138 | name = ", ".join(_get_name(t.account) for t in toots) 139 | 140 | if toot_type == "follow": 141 | return {"text": f"👤 {name} followed you."} 142 | 143 | if toot_type == "reblog": 144 | text = f"🔁 {name} boosted your toot." 145 | elif toot_type == "favourite": 146 | text = f"⭐ {name} favorited your toot." 147 | else: # unsupported type 148 | assert toot_type != "mention" # mentions are handled with toots2replies 149 | return {} 150 | 151 | toot = toots[0].status 152 | text += f"\n\n[{v2emoji[toot.visibility]} {toot.created_at.strftime(STRFORMAT)}]({toot.url})" 153 | return {"text": text, "html": toot.content} 154 | 155 | 156 | def get_extension(resp: requests.Response) -> str: 157 | disp = resp.headers.get("content-disposition") 158 | if disp is not None and re.findall("filename=(.+)", disp): 159 | fname = re.findall("filename=(.+)", disp)[0].strip('"') 160 | else: 161 | fname = resp.url.split("/")[-1].split("?")[0].split("#")[0] 162 | if "." in fname: 163 | ext = "." + fname.rsplit(".", maxsplit=1)[-1] 164 | else: 165 | ctype = resp.headers.get("content-type", "").split(";")[0].strip().lower() 166 | ext = mimetypes.guess_extension(ctype) or "" 167 | return ext 168 | 169 | 170 | def get_user(m, user_id) -> Any: 171 | user = None 172 | if user_id.isdigit(): 173 | user = m.account(user_id) 174 | else: 175 | user_id = user_id.lstrip("@").lower() 176 | ids = (user_id, user_id.split("@")[0]) 177 | for a in m.account_search(user_id): 178 | if a.acct.lower() in ids: 179 | user = a 180 | break 181 | return user 182 | 183 | 184 | def download_file(bot: DeltaBot, url: str, default_extension="") -> str: 185 | """Download a file and save the file in the bot's blobs folder.""" 186 | with web.get(url) as resp: 187 | ext = get_extension(resp) or default_extension 188 | with NamedTemporaryFile( 189 | dir=bot.account.get_blobdir(), suffix=ext, delete=False 190 | ) as temp_file: 191 | path = temp_file.name 192 | with open(path, "wb") as file: 193 | file.write(resp.content) 194 | return path 195 | 196 | 197 | def normalize_url(url: str) -> str: 198 | if url.startswith("http://"): 199 | url = "https://" + url[4:] 200 | elif not url.startswith("https://"): 201 | url = "https://" + url 202 | return url.rstrip("/") 203 | 204 | 205 | def getdefault(bot: DeltaBot, key: str, value: Optional[str] = None) -> str: 206 | val = bot.get(key, scope=_scope) 207 | if val is None and value is not None: 208 | bot.set(key, value, scope=_scope) 209 | val = value 210 | return val 211 | 212 | 213 | def get_database_path(bot: DeltaBot) -> str: 214 | path = os.path.join(os.path.dirname(bot.account.db_path), _scope) 215 | if not os.path.exists(path): 216 | os.makedirs(path) 217 | return os.path.join(path, "sqlite.db") 218 | 219 | 220 | def get_profile(bot: DeltaBot, masto: Mastodon, username: Optional[str] = None) -> str: 221 | me = masto.me() 222 | if not username: 223 | user = me 224 | else: 225 | user = get_user(masto, username) 226 | if user is None: 227 | return "❌ Invalid user" 228 | 229 | text = f"{_get_name(user)}:\n\n" 230 | fields = "" 231 | for f in user.fields: 232 | fields += f"{html2text(f.name).strip()}: {html2text(f.value).strip()}\n" 233 | if fields: 234 | text += fields + "\n\n" 235 | text += html2text(user.note).strip() 236 | text += f"\n\nToots: {user.statuses_count}\nFollowing: {user.following_count}\nFollowers: {user.followers_count}" 237 | if user.id != me.id: 238 | rel = masto.account_relationships(user)[0] 239 | if rel["followed_by"]: 240 | text += "\n[follows you]" 241 | elif rel["blocked_by"]: 242 | text += "\n[blocked you]" 243 | text += "\n" 244 | if rel["following"] or rel["requested"]: 245 | action = "unfollow" 246 | else: 247 | action = "follow" 248 | prefix = getdefault(bot, "cmd_prefix", "") 249 | text += f"\n/{prefix}{action}_{user.id}" 250 | action = "unmute" if rel["muting"] else "mute" 251 | text += f"\n/{prefix}{action}_{user.id}" 252 | action = "unblock" if rel["blocking"] else "block" 253 | text += f"\n/{prefix}{action}_{user.id}" 254 | text += f"\n/{prefix}dm_{user.id}" 255 | text += TOOT_SEP 256 | toots = masto.account_statuses(user, limit=10) 257 | text += TOOT_SEP.join(toots2texts(bot, reversed(toots))) 258 | return text 259 | 260 | 261 | def listen_to_mastodon(bot: DeltaBot) -> None: 262 | while True: 263 | try: 264 | _check_mastodon(bot) 265 | except Exception as ex: 266 | bot.logger.exception(ex) 267 | 268 | 269 | def _check_mastodon(bot: DeltaBot) -> None: 270 | while True: 271 | bot.logger.debug("Checking Mastodon") 272 | instances: dict = {} 273 | with session_scope() as session: 274 | acc_count = session.query(Account).count() 275 | bot.logger.debug(f"Accounts to check: {acc_count}") 276 | for acc in session.query(Account): 277 | instances.setdefault(acc.url, []).append( 278 | ( 279 | acc.addr, 280 | acc.token, 281 | acc.home, 282 | acc.last_home, 283 | acc.muted_home, 284 | acc.notifications, 285 | acc.last_notif, 286 | acc.muted_notif, 287 | ) 288 | ) 289 | 290 | start_time = time.time() 291 | instances_count = len(instances) 292 | total_acc = acc_count 293 | while instances: 294 | bot.logger.debug( 295 | f"Check: {acc_count} accounts across {instances_count} instances remaining..." 296 | ) 297 | for key in list(instances.keys()): 298 | ( 299 | addr, 300 | token, 301 | home_chat, 302 | last_home, 303 | muted_home, 304 | notif_chat, 305 | last_notif, 306 | muted_notif, 307 | ) = instances[key].pop() 308 | acc_count -= 1 309 | if not instances[key]: 310 | instances.pop(key) 311 | instances_count -= 1 312 | bot.logger.debug(f"{addr}: Checking account ({key})") 313 | try: 314 | masto = get_mastodon(key, token) 315 | _check_notifications( 316 | bot, masto, addr, notif_chat, last_notif, muted_notif 317 | ) 318 | if muted_home: 319 | bot.logger.debug(f"{addr}: Ignoring Home timeline (muted)") 320 | else: 321 | _check_home(bot, masto, addr, home_chat, last_home) 322 | bot.logger.debug(f"{addr}: Done checking account") 323 | except MastodonUnauthorizedError as ex: 324 | bot.logger.exception(ex) 325 | chats: List[int] = [] 326 | with session_scope() as session: 327 | acc = session.query(Account).filter_by(addr=addr).first() 328 | if acc: 329 | chats.extend(dmchat.chat_id for dmchat in acc.dm_chats) 330 | chats.append(acc.home) 331 | chats.append(acc.notifications) 332 | session.delete(acc) 333 | for chat_id in chats: 334 | try: 335 | bot.get_chat(chat_id).remove_contact(bot.self_contact) 336 | except ValueError: 337 | pass 338 | 339 | bot.get_chat(addr).send_text( 340 | f"❌ ERROR Your account was logged out: {ex}" 341 | ) 342 | except (MastodonNetworkError, MastodonServerError) as ex: 343 | bot.logger.exception(ex) 344 | except Exception as ex: # noqa 345 | bot.logger.exception(ex) 346 | bot.get_chat(addr).send_text( 347 | f"❌ ERROR while checking your account: {ex}" 348 | ) 349 | time.sleep(2) 350 | elapsed = int(time.time() - start_time) 351 | delay = max(int(getdefault(bot, "delay")) - elapsed, 10) 352 | bot.logger.info( 353 | f"Done checking {total_acc} accounts, sleeping for {delay} seconds..." 354 | ) 355 | time.sleep(delay) 356 | 357 | 358 | def send_toot( 359 | masto: Mastodon, 360 | text: Optional[str] = None, 361 | filename: Optional[str] = None, 362 | visibility: Optional[str] = None, 363 | in_reply_to: Optional[str] = None, 364 | ) -> None: 365 | if filename: 366 | if filename.endswith(".aac"): 367 | aac_file = AudioSegment.from_file(filename, "aac") 368 | filename = filename[:-4] + ".mp3" 369 | aac_file.export(filename, format="mp3") 370 | media = [masto.media_post(filename).id] 371 | if in_reply_to: 372 | masto.status_reply( 373 | masto.status(in_reply_to), text, media_ids=media, visibility=visibility 374 | ) 375 | else: 376 | masto.status_post(text, media_ids=media, visibility=visibility) 377 | elif text: 378 | if in_reply_to: 379 | masto.status_reply(masto.status(in_reply_to), text, visibility=visibility) 380 | else: 381 | masto.status_post(text, visibility=visibility) 382 | 383 | 384 | def get_client(session, api_url) -> tuple: 385 | client = session.query(Client).filter_by(url=api_url).first() 386 | if client: 387 | return client.id, client.secret 388 | 389 | try: 390 | client_id, client_secret = Mastodon.create_app( 391 | client_name="DeltaChat Bridge", 392 | website="https://github.com/simplebot-org/simplebot_mastodon", 393 | redirect_uris="urn:ietf:wg:oauth:2.0:oob", 394 | api_base_url=api_url, 395 | session=web, 396 | ) 397 | except Exception: # noqa 398 | client_id, client_secret = None, None 399 | session.add(Client(url=api_url, id=client_id, secret=client_secret)) 400 | return client_id, client_secret 401 | 402 | 403 | def get_mastodon(api_url: str, token: Optional[str] = None, **kwargs) -> Mastodon: 404 | return Mastodon( 405 | access_token=token, 406 | api_base_url=api_url, 407 | ratelimit_method="throw", 408 | session=web, 409 | **kwargs, 410 | ) 411 | 412 | 413 | def get_mastodon_from_msg(message: Message) -> Optional[Mastodon]: 414 | api_url, token = "", "" 415 | with session_scope() as session: 416 | acc = get_account_from_msg(message, session) 417 | if acc: 418 | api_url, token = acc.url, acc.token 419 | return get_mastodon(api_url, token) if api_url else None 420 | 421 | 422 | def get_account_from_msg(message: Message, session) -> Optional[Account]: 423 | acc = get_account_from_chat(message.chat, session) 424 | if not acc: 425 | addr = message.get_sender_contact().addr 426 | acc = session.query(Account).filter_by(addr=addr).first() 427 | return acc 428 | 429 | 430 | def get_account_from_chat(chat: Chat, session) -> Optional[Account]: 431 | if chat.is_multiuser(): 432 | acc = ( 433 | session.query(Account) 434 | .filter((Account.home == chat.id) | (Account.notifications == chat.id)) 435 | .first() 436 | ) 437 | if not acc: 438 | dmchat = session.query(DmChat).filter_by(chat_id=chat.id).first() 439 | if dmchat: 440 | acc = dmchat.account 441 | else: 442 | acc = None 443 | return acc 444 | 445 | 446 | def account_action(action: str, payload: str, message: Message) -> str: 447 | if not payload: 448 | return "❌ Wrong usage" 449 | 450 | masto = get_mastodon_from_msg(message) 451 | if masto: 452 | if payload.isdigit(): 453 | user_id = payload 454 | else: 455 | user_id = get_user(masto, payload) 456 | if user_id is None: 457 | return "❌ Invalid user" 458 | getattr(masto, action)(user_id) 459 | return "" 460 | return "❌ You are not logged in" 461 | 462 | 463 | def _get_name(macc) -> str: 464 | isbot = "[BOT] " if macc.bot else "" 465 | if macc.display_name: 466 | return isbot + f"{macc.display_name} (@{macc.acct})" 467 | return isbot + macc.acct 468 | 469 | 470 | def _handle_dms(dms: list, bot: DeltaBot, addr: str, notif_chat: int) -> None: 471 | def _get_chat_id(acct) -> int: 472 | with session_scope() as session: 473 | dmchat = ( 474 | session.query(DmChat).filter_by(acc_addr=addr, contact=acct).first() 475 | ) 476 | if dmchat: 477 | chat_id = dmchat.chat_id 478 | else: 479 | chat_id = 0 480 | return chat_id 481 | 482 | prefix = getdefault(bot, "cmd_prefix", "") 483 | chats: Dict[str, int] = {} 484 | replies = Replies(bot, bot.logger) 485 | for dm in reversed(dms): 486 | reply = toot2reply(prefix, dm) 487 | if reply.get("filename"): 488 | try: 489 | reply["filename"] = download_file(bot, reply["filename"]) 490 | except Exception as ex: 491 | bot.logger.exception(ex) 492 | text = reply.get("text", "") 493 | if not text.startswith("http"): 494 | text = "\n" + text 495 | reply["text"] = reply["filename"] + "\n" + text 496 | if not reply: 497 | continue 498 | 499 | acct = dm.account.acct 500 | chat_id = chats.get(acct, 0) 501 | if not chat_id: 502 | chat_id = chats[acct] = _get_chat_id(acct) 503 | 504 | if chat_id: 505 | chat = bot.get_chat(chat_id) 506 | else: 507 | chat = bot.create_group(acct, bot.get_chat(notif_chat).get_contacts()) 508 | chats[acct] = chat.id 509 | with session_scope() as session: 510 | session.add(DmChat(chat_id=chat.id, contact=acct, acc_addr=addr)) 511 | 512 | try: 513 | path = download_file(bot, dm.account.avatar_static, ".jpg") 514 | chat.set_profile_image(path) 515 | except ValueError as err: 516 | bot.logger.exception(err) 517 | os.remove(path) 518 | except Exception as err: 519 | bot.logger.exception(err) 520 | 521 | replies.add(**reply, chat=chat) 522 | replies.send_reply_messages() 523 | 524 | 525 | def _check_notifications( 526 | bot: DeltaBot, 527 | masto: Mastodon, 528 | addr: str, 529 | notif_chat: int, 530 | last_id: str, 531 | muted_notif: bool, 532 | ) -> None: 533 | dms = [] 534 | notifications = [] 535 | bot.logger.debug(f"{addr}: Getting Notifications (last_id={last_id})") 536 | toots = masto.notifications(min_id=last_id, limit=100) 537 | if toots: 538 | with session_scope() as session: 539 | acc = session.query(Account).filter_by(addr=addr).first() 540 | acc.last_notif = last_id = toots[0].id 541 | for toot in toots: 542 | if ( 543 | toot.type == "mention" 544 | and toot.status.visibility == Visibility.DIRECT 545 | and len(toot.status.mentions) == 1 546 | ): 547 | content = toot.status.content 548 | if not any(keyword in content for keyword in SPAM): 549 | dms.append(toot.status) 550 | elif not muted_notif or toot.type not in MUTED_NOTIFICATIONS: 551 | notifications.append(toot) 552 | 553 | if dms: 554 | bot.logger.debug(f"{addr}: Direct Messages: {len(dms)} new entries") 555 | _handle_dms(dms, bot, addr, notif_chat) 556 | 557 | bot.logger.debug( 558 | f"{addr}: Notifications: {len(notifications)} new entries (last_id={last_id})" 559 | ) 560 | if notifications: 561 | reblogs: dict[str, AttribAccessDict] = {} 562 | favs: dict[str, AttribAccessDict] = {} 563 | follows = [] 564 | mentions = [] 565 | for toot in reversed(notifications): 566 | if toot.type == "reblog": 567 | reblogs.setdefault(toot.status.id, []).append(toot) 568 | elif toot.type == "favourite": 569 | favs.setdefault(toot.status.id, []).append(toot) 570 | elif toot.type == "follow": 571 | follows.append(toot) 572 | else: 573 | mentions.append(toot.status) 574 | notifs = [*reblogs.values(), *favs.values()] 575 | if follows: 576 | notifs.append(follows) 577 | chat = bot.get_chat(notif_chat) 578 | replies = Replies(bot, bot.logger) 579 | for reply in notif2replies(notifs): 580 | replies.add(**reply, chat=chat) 581 | replies.send_reply_messages() 582 | for reply in toots2replies(bot, mentions): 583 | replies.add(**reply, chat=chat) 584 | replies.send_reply_messages() 585 | 586 | 587 | def _check_home( 588 | bot: DeltaBot, masto: Mastodon, addr: str, home_chat: int, last_id: str 589 | ) -> None: 590 | me = masto.me() 591 | bot.logger.debug(f"{addr}: Getting Home timeline (last_id={last_id})") 592 | toots = masto.timeline_home(min_id=last_id, limit=100) 593 | if toots: 594 | with session_scope() as session: 595 | acc = session.query(Account).filter_by(addr=addr).first() 596 | acc.last_home = last_id = toots[0].id 597 | toots = [ 598 | toot for toot in toots if me.id not in [acc.id for acc in toot.mentions] 599 | ] 600 | bot.logger.debug(f"{addr}: Home: {len(toots)} new entries (last_id={last_id})") 601 | if toots: 602 | chat = bot.get_chat(home_chat) 603 | replies = Replies(bot, bot.logger) 604 | for reply in toots2replies(bot, reversed(toots)): 605 | replies.add(**reply, chat=chat) 606 | replies.send_reply_messages() 607 | -------------------------------------------------------------------------------- /tests/test_plugin.py: -------------------------------------------------------------------------------- 1 | class TestPlugin: 2 | """Offline tests""" 3 | 4 | def test_logout(self, mocker) -> None: 5 | msg = mocker.get_one_reply("/logout") 6 | assert "❌" in msg.text 7 | 8 | def test_bio(self, mocker) -> None: 9 | msg = mocker.get_one_reply("/bio") 10 | assert "❌" in msg.text 11 | 12 | def test_avatar(self, mocker) -> None: 13 | msg = mocker.get_one_reply("/avatar") 14 | assert "❌" in msg.text 15 | 16 | def test_dm(self, mocker) -> None: 17 | msg = mocker.get_one_reply("/dm") 18 | assert "❌" in msg.text 19 | 20 | def test_reply(self, mocker) -> None: 21 | msg = mocker.get_one_reply("/reply") 22 | assert "❌" in msg.text 23 | 24 | def test_star(self, mocker) -> None: 25 | msg = mocker.get_one_reply("/star") 26 | assert "❌" in msg.text 27 | 28 | def test_boost(self, mocker) -> None: 29 | msg = mocker.get_one_reply("/boost") 30 | assert "❌" in msg.text 31 | 32 | def test_open(self, mocker) -> None: 33 | msg = mocker.get_one_reply("/open") 34 | assert "❌" in msg.text 35 | 36 | def test_follow(self, mocker) -> None: 37 | msg = mocker.get_one_reply("/follow") 38 | assert "❌" in msg.text 39 | 40 | def test_unfollow(self, mocker) -> None: 41 | msg = mocker.get_one_reply("/unfollow") 42 | assert "❌" in msg.text 43 | 44 | def test_mute(self, mocker) -> None: 45 | msg = mocker.get_one_reply("/mute") 46 | assert "❌" in msg.text 47 | 48 | def test_unmute(self, mocker) -> None: 49 | msg = mocker.get_one_reply("/unmute") 50 | assert "❌" in msg.text 51 | 52 | def test_block(self, mocker) -> None: 53 | msg = mocker.get_one_reply("/block") 54 | assert "❌" in msg.text 55 | 56 | def test_unblock(self, mocker) -> None: 57 | msg = mocker.get_one_reply("/unblock") 58 | assert "❌" in msg.text 59 | 60 | def test_profile(self, mocker) -> None: 61 | msg = mocker.get_one_reply("/profile") 62 | assert "❌" in msg.text 63 | 64 | def test_local(self, mocker) -> None: 65 | msg = mocker.get_one_reply("/local") 66 | assert "❌" in msg.text 67 | 68 | def test_public(self, mocker) -> None: 69 | msg = mocker.get_one_reply("/public") 70 | assert "❌" in msg.text 71 | 72 | def test_tag(self, mocker) -> None: 73 | msg = mocker.get_one_reply("/tag") 74 | assert "❌" in msg.text 75 | 76 | def test_search(self, mocker) -> None: 77 | msg = mocker.get_one_reply("/search") 78 | assert "❌" in msg.text 79 | --------------------------------------------------------------------------------