1
0
Fork 0
This commit is contained in:
Nathan Price 2025-01-05 17:12:38 -05:00
commit 3577bf15ce
Signed by: gravityfargo
SSH key fingerprint: SHA256:bjq+uA1U+9bFMd70q2wdNtwaYxGv84IBXalnYvZDKmg
12 changed files with 1925 additions and 0 deletions

104
.gitignore vendored Normal file
View file

@ -0,0 +1,104 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# 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/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# dotenv
.env
# virtualenv
.venv
venv/
ENV/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
poc*
/docs/
.idea/*

29
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,29 @@
{
"[python]": {
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.organizeImports": "explicit"
},
"editor.defaultFormatter": "charliermarsh.ruff"
},
"[properties]": {
"editor.formatOnSave": false,
"editor.formatOnType": false,
"editor.formatOnPaste": false
},
"editor.formatOnSave": true,
"files.exclude": {
"**/.git": true,
"**/__pycache__": true,
"**/.mypy_cache": true,
"**/.pytest_cache": true,
},
"files.associations": {
"*.local": "properties"
},
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
}

15
Examples/telegram.py Normal file
View file

@ -0,0 +1,15 @@
import os
from dotenv import load_dotenv
from envoyer import Telegram
load_dotenv()
TOKEN = os.getenv("TELEGRAM_API_TOKEN")
# provider = Telegram(TOKEN)
# provider.get_chats()
CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
provider = Telegram(TOKEN, CHAT_ID)
provider.send("Hello, World!")

9
LICENSE Normal file
View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2025 gravityfargo
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.

0
README.md Normal file
View file

3
envoyer/__init__.py Normal file
View file

@ -0,0 +1,3 @@
from envoyer.telegram import Telegram
__all__ = ["Telegram"]

1
envoyer/_version.py Normal file
View file

@ -0,0 +1 @@
__version__ = "0.0.0"

89
envoyer/telegram.py Normal file
View file

@ -0,0 +1,89 @@
"""_summary_.
https://core.telegram.org/bots/features#creating-a-new-bot
- send a message to the bot @BotFather
- follow the instructions to create a new bot
Get the chat ID:
Group:
- Send the message `/my_id @MyBotNameBot` to the group
DM
- Send any message to the bot
`Telegram(token=your_token).get_chats()`
Example:
---------
```python
import os
from dotenv import load_dotenv
from envoye import Telegram
load_dotenv()
TOKEN = os.getenv("TELEGRAM_API_TOKEN")
CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
provider = Telegram(token=TOKEN, chat_id=CHAT_ID)
provider.get_chats()
```
"""
from dataclasses import dataclass
from typing import Optional
import requests
from rich import print
from rich.table import Table
@dataclass
class Telegram:
"""Send Telegram notifications."""
token: Optional[str] = None
chat_id: Optional[str] = None
def __post_init__(self) -> None:
if self.token is None:
raise ValueError("Telegram token is required")
def get_chats(self) -> None:
"""Return the chat ID for the bot."""
url = f"https://api.telegram.org/bot{self.token}/getUpdates"
data = requests.get(url).json()
if not data["ok"]:
print(data)
raise ValueError("Error getting bot's chats.")
if len(data["result"]) == 0:
raise ValueError("Bot has no chats.")
table = Table(title="Telegram Bot's Chats")
table.add_column("Chat ID")
table.add_column("Type")
table.add_column("User's Name")
table.add_column("Group Title")
for c in data["result"]:
chat = c["message"]["chat"]
row = []
row.extend([str(chat["id"]), chat["type"]])
if chat["type"] == "group":
row.extend(["", chat["title"]])
else:
row.append(f"{chat['first_name']} {chat.get('last_name', '')}")
table.add_row(*row)
print(table)
def send(self, message: str) -> None:
"""Send the message."""
if self.chat_id is None:
raise ValueError("Chat ID is required")
url = f"https://api.telegram.org/bot{self.token}/sendMessage"
url += f"?chat_id={self.chat_id}&text={message}"
requests.get(url)

1533
poetry.lock generated Normal file

File diff suppressed because it is too large Load diff

2
poetry.toml Normal file
View file

@ -0,0 +1,2 @@
[virtualenvs]
in-project = true

140
pyproject.toml Normal file
View file

@ -0,0 +1,140 @@
[tool.poetry]
authors = ["Nathan Price <nathan@gravityfargo.dev>"]
classifiers = [
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python",
]
description = ""
exclude = ["tests"]
include = ["LICENSE"]
license = "MIT"
name = "envoyer"
readme = "README.md"
repository = "https://forgejo.gravityfargo.dev/gravityfargo/envoyer"
version = "0.0.0"
[tool.poetry.dependencies]
python = "^3.12"
requests = "^2.32.3"
rich = "^13.9.4"
[tool.poetry.group.dev.dependencies]
mypy = "^1.13.0"
poetry-dynamic-versioning = { extras = ["plugin"], version = "^1.4.1" }
pytest = "^8.3.3"
pytest-cov = "^6.0.0"
python-dotenv = "^1.0.1"
ruff = "^0.8.5"
types-requests = "^2.32.0.20241016"
[build-system]
build-backend = "poetry_dynamic_versioning.backend"
requires = ["poetry-core>=1.0.0", "poetry-dynamic-versioning>=1.0.0,<2.0.0"]
[tool.poetry-dynamic-versioning]
enable = true
style = "semver"
vcs = "git"
[tool.poetry-dynamic-versioning.files."envoyer/_version.py"]
initial-content = """
__version__ = "0.0.0"
"""
persistent-substitution = true
[tool.pytest.ini_options]
addopts = "--cov-report term-missing --cov-report term:skip-covered --cov-report xml --cov=envoyer --maxfail=1 --last-failed --capture=no -vv"
testpaths = ["tests"]
[tool.coverage.run]
omit = ["__init__.py", "__main__.py", "_version.py"]
[tool.coverage.report]
# Regexes for lines to exclude from consideration
exclude_also = ["def __repr__", "def main", "if __name__ == .__main__.:"]
[tool.mypy]
ignore_missing_imports = true
[tool.ruff]
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".ipynb_checkpoints",
".mypy_cache",
".nox",
".pants.d",
".pyenv",
".pytest_cache",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
".vscode",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"site-packages",
"venv",
]
fix = true
indent-width = 4
line-length = 120
src = ["envoyer", "tests"]
[tool.ruff.lint]
fixable = ["ALL"]
ignore = [
"ANN003", # missing-type-kwargs
"ANN204", # missing-return-type-special-method
"ANN401", # any-type
"D100", # undocumented-public-module
"D105", # undocumented-magic-method
"PLW2901", # redefined-loop-name
]
select = [
"ANN", # flake8-annotations
"C4", # flake8-comprehensions
"D", # pydocstyle
"E", # pycodestyle
"F", # pyflakes
"I", # isort
"N", # pep8-naming
"PIE", # flake8-pie
"PL", # Pylint
"PT", # flake8-pytest-style
"PTH", # flake8-use-pathlib
"SIM", # flake8-simplify
"SLOT", # flake8-slots
"W", # pycodestyle
]
unfixable = []
# [tool.ruff.lint.flake8-annotations]
# suppress-dummy-args = true
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["D"]
"tests/**.py" = [
"ANN",
"D",
"F841", # unused-variable
]
[tool.ruff.lint.pydocstyle]
convention = "numpy"
[tool.ruff.lint.isort]
case-sensitive = true

0
tests/__init__.py Normal file
View file