Skip to content

Commit

Permalink
Updating dependencies (#22)
Browse files Browse the repository at this point in the history
* Started to updated dependencies
* Pytest, requests
* Added pre-commit, ran pre-commit, updated chat_id -> user_chat_id in chatjoinrequests, added constructors to extract chat data and chat request data
  • Loading branch information
why-not-try-calmer authored Apr 21, 2023
1 parent 676dbb2 commit 6f8542a
Show file tree
Hide file tree
Showing 17 changed files with 251 additions and 174 deletions.
2 changes: 1 addition & 1 deletion .github/FUNDING.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@
# issuehunt: # Replace with a single IssueHunt username
# otechie: # Replace with a single Otechie username
# lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: ['https://www.buymeacoffee.com/WhyNotTryCalmer']
custom: ['https://www.buymeacoffee.com/WhyNotTryCalmer']
58 changes: 29 additions & 29 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
name: Deployment

on:
workflow_run:
workflows: ["Publish"]
branches: [master]
types:
- completed

workflow_dispatch:

jobs:
deploy_to_production:
name: Connect and deploy
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v3

- name: Connect And Pull
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.PROD_HOST }}
username: root
key: ${{ secrets.PROD_KEY }}
passphrase: ${{ secrets.PROD_PASSWD }}
script: |
cd /opt/app
./refresh ringo
name: Deployment

on:
workflow_run:
workflows: ["Publish"]
branches: [master]
types:
- completed

workflow_dispatch:

jobs:
deploy_to_production:
name: Connect and deploy
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v3

- name: Connect And Pull
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.PROD_HOST }}
username: root
key: ${{ secrets.PROD_KEY }}
passphrase: ${{ secrets.PROD_PASSWD }}
script: |
cd /opt/app
./refresh ringo
25 changes: 25 additions & 0 deletions .github/workflows/precommit.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Check pre-commit

on:
pull_request:
branches:
- master

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2

- name: Install pre-commit
run: pip install pre-commit

- name: Run pre-commit
run: pre-commit run --all-files --show-diff-on-failure --verbose

- name: Pre-commit failed ! Read this
if: failure()
run: |
echo 'To ensure your code is properly formatted, run: pip install pre-commit; pre-commit install;'
echo 'Fix your current code with: pre-commit run --all-files'
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ on:
workflow_run:
workflows: ["Test"]
branches: [master]
types:
types:
- completed

workflow_dispatch:
Expand Down
29 changes: 29 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: mixed-line-ending
args:
- "--fix=lf"

- repo: https://github.com/myint/autoflake
rev: v2.1.1
hooks:
- id: autoflake
args:
- "--in-place"
- "--remove-all-unused-imports"
- "--remove-unused-variables"

- repo: https://github.com/pycqa/isort
rev: "5.12.0"
hooks:
- id: isort
args: ["--profile", "black"]

- repo: https://github.com/psf/black
rev: "23.3.0"
hooks:
- id: black
12 changes: 0 additions & 12 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,10 @@ COPY ./requirements.txt .
ENV PIPENV_VENV_IN_PROJECT=1
RUN pipenv install

# Azure handles TLS
# RUN openssl req -subj \
# "/C=CH/ST=Bern/L=Bern/O=WhoCares /OU=Again/CN=SoNosey" \
# -newkey rsa:2048 -sha256 -nodes \
# -keyout private.key -x509 -days 3650 -out cert.pem

# runner
FROM python:3.10-slim-bullseye
WORKDIR /opt/app

# runnable code
COPY . .
COPY --from=builder /opt/app/.venv/ .venv/

# Azure handles TLS
# COPY --from=builder /opt/app/cert.pem cert.pem
# COPY --from=builder /opt/app/private.key private.key

CMD . .venv/bin/activate && python -m app
1 change: 0 additions & 1 deletion Procfile

This file was deleted.

10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

## Overview

This bot provides a simple click-based verification workflow for your Telegram users. It requires that you have enabled the options `Only members can send messages` as well as `Use chat join requests`; only the latter is strictly necessary but goes hand in hand with the former.
This bot provides a simple click-based verification workflow for your Telegram users. It requires that you have enabled the options `Only members can send messages` as well as `Use chat join requests`; only the latter is strictly necessary but goes hand in hand with the former.

You can see [the bot](https://t.me/alert_me_and_my_chat_bot) in action [here](https://t.me/PopOS_en).

If you like the bot, feel free to use it in your own chats, fork this repository or even pay a coffee or a beer to the developer. At any rate please mind the LICENSE.
If you like the bot, feel free to use it in your own chats, fork this repository or even pay a coffee or a beer to the developer. At any rate please mind the LICENSE.

## How it works

Expand All @@ -34,7 +34,7 @@ The bot uses exactly two commands in addition to `/help` (which aliases to `/sta
- `chat_id`: the chat_id of the chat where the bot should listen for join requests (you cannot manually set this value)
- `chat_url`: the full url (https://t.me/...) of the chat where the bot should listen for join requests (you can and __should__ set this value)
- `mode <auto | manual | questionnaire>`: see the previous section for explanations
- `helper_chat_id_`: chat_id of the chat to which the both should forward join requests notifications (only used in __manual__ mode)
- `helper_chat_id_`: chat_id of the chat to which the both should forward join requests notifications (only used in __manual__ mode)
- `verification_msg`: the message the bot should send to users trying to verify after landing a join requests. Naturall it's not convenient to set a long verification message in this way, so for that key it might be preferable to use a line break, as in:
```
/set mode auto verification_message
Expand All @@ -48,7 +48,7 @@ The bot uses exactly two commands in addition to `/help` (which aliases to `/sta
Question 2: ...
Question 3: ...
Thanks very much! Admins will now accept or decline your join request.
```
```
- `paused <on | off>`: _off_ pauses the bot for this chat, _off_ makes it active
- `show_join_time <on | off>`: _off_ does not show the time it took for a user to join the target chat after being sent an invite, _on_ shows it
- `changelog < on | off>`: _off_ lets you opt-out of changelog notification messages
Expand Down Expand Up @@ -81,4 +81,4 @@ If you want to have the bot listen to a custom port, there is the option to add
4. Deploy: `docker run -p <HOST_PORT>:<CUSTOM_CONTAINER_PORT> --env-file .env localhost/ringo`
Finally to start the bot run `python -m app` if you want to register a webhook hook and receive updates with the built-in server. Otherwise start with `python -m app --polling`.
Finally to start the bot run `python -m app` if you want to register a webhook hook and receive updates with the built-in server. Otherwise start with `python -m app --polling`.
12 changes: 4 additions & 8 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@
from os import environ
from sys import stdout

from motor.motor_asyncio import (
AsyncIOMotorClient,
AsyncIOMotorCollection,
AsyncIOMotorDatabase,
)
from motor.motor_asyncio import AsyncIOMotorClient
from telegram.warnings import PTBUserWarning
from toml import loads

Expand All @@ -23,9 +19,9 @@

""" Database """
client = AsyncIOMotorClient(environ["MONGO_CONN_STRING"])
db: AsyncIOMotorDatabase = client["alert-me"]
chats: AsyncIOMotorCollection = db["chats"]
logs: AsyncIOMotorCollection = db["logs"]
db = client["alert-me"]
chats = db["chats"]
logs = db["logs"]
clean_up_db = True if environ.get("CLEAN_UP_DB", False) == "true" else False

""" Setup strings """
Expand Down
22 changes: 12 additions & 10 deletions app/__main__.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
from sys import argv
from os import environ
from sys import argv

from telegram import Message
from telegram.ext import (
Application,
CallbackQueryHandler,
ChatJoinRequestHandler,
MessageHandler,
CommandHandler,
CallbackQueryHandler,
MessageHandler,
filters,
)
from telegram.ext.filters import MessageFilter
from telegram import Message

from app import dialog_manager
from app.handlers import (
admin_op,
answering_help,
expected_dialog,
getting_status,
replying_to_bot,
wants_to_join,
has_joined,
processing_cbq,
answering_help,
setting_bot,
replying_to_bot,
resetting,
has_joined,
setting_bot,
wants_to_join,
)
from app import dialog_manager


class Dialog(MessageFilter):
Expand Down Expand Up @@ -68,6 +69,7 @@ def registerHandlers(app: Application):
"""

from os import path

import uvloop

TOKEN = environ["TOKEN"]
Expand Down
23 changes: 9 additions & 14 deletions app/db.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
from functools import reduce
from asyncio import as_completed, gather, sleep
from datetime import datetime, timedelta
from os import environ
from typing import Optional
from telegram.ext import ContextTypes

from pymongo.collection import ReturnDocument
from pymongo.results import DeleteResult, UpdateResult, InsertOneResult
from datetime import datetime, timedelta
from asyncio import as_completed, gather, sleep
from pymongo.results import DeleteResult, InsertOneResult, UpdateResult
from telegram.ext import ContextTypes

from app import chats, logs
from app import chats, clean_up_db, logs
from app.types import (
ChatId,
Log,
Questionnaire,
Operation,
ServiceLog,
MessageId,
Operation,
Questionnaire,
ServiceLog,
Settings,
Status,
Expand All @@ -24,7 +23,6 @@
UserWithName,
)
from app.utils import mark_successful_coroutines, run_coroutines_masked
from app import clean_up_db

""" Settings """

Expand Down Expand Up @@ -73,7 +71,6 @@ async def remove_chats(chats_ids: list[ChatId]) -> DeleteResult:
async def add_pending(
chat_id: ChatId, user_id: UserId, message_id: MessageId
) -> UpdateResult:

user_key = f"pending_{user_id}"
payload = {"message_id": message_id, "at": datetime.now()}
return await chats.find_one_and_update(
Expand Down Expand Up @@ -230,7 +227,6 @@ async def get_users_at(chat_id: ChatId, user_ids: list[UserId]) -> list[datetime

async def log(to_log: Log) -> InsertOneResult | UpdateResult:
match to_log:

case ServiceLog():
return await logs.insert_one(to_log.as_dict())

Expand Down Expand Up @@ -308,7 +304,6 @@ async def background_task(context: ContextTypes.DEFAULT_TYPE | None) -> None | i

# Collecting results
async for u in cursor:

if not "user_id" in u or not "chat_id" in u:
continue

Expand All @@ -322,7 +317,6 @@ async def background_task(context: ContextTypes.DEFAULT_TYPE | None) -> None | i
to_notify.append(User(u["user_id"], u["chat_id"]))

if tried_6h_ago_and_got_alert(u):

if u["chat_id"] in banners:
if not hh(uid, cid) in banned:
to_ban.append(User(u["user_id"], u["chat_id"]))
Expand All @@ -341,6 +335,7 @@ async def background_task(context: ContextTypes.DEFAULT_TYPE | None) -> None | i
"chat_id": {"$in": [u.chat_id for u in to_deny_and_remove]},
}
)

# Declining pending join requests with exceptions masked
# as there is no way to determine with certainty if the target join request was taken back or not
async def deny_notify(user: User):
Expand Down
Loading

0 comments on commit 6f8542a

Please sign in to comment.