Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upd tg-bot to v20 #8

Merged
merged 5 commits into from
Jul 6, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions .flake8

This file was deleted.

5 changes: 0 additions & 5 deletions .isort.cfg

This file was deleted.

4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ install-deps: deps
pip-sync requirements.txt

deps:
pip-compile requirements.in
pip-compile --resolver=backtracking --output-file=requirements.txt pyproject.toml

dev-deps: deps
pip-compile dev-requirements.in
pip-compile --resolver=backtracking --extra=dev --output-file=dev-requirements.txt pyproject.toml

lint:
flake8 *.py
Expand Down
51 changes: 18 additions & 33 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,18 @@
from typing import Optional

import os
from telegram import Message, Update
from telegram.ext import CallbackContext, Dispatcher, MessageHandler, Updater
from telegram.ext.filters import BaseFilter, Filters
from telegram.ext import Application, ContextTypes, MessageHandler
from telegram.ext.filters import TEXT, BaseFilter

import rekognition
import text
from filters import ContainsLink, ContainsTelegramContact, ContainsThreeOrMoreEmojies, IsMedia, IsMessageOnBehalfOfChat, with_default_filters
from helpers import DB_ENABLED, enable_logging, in_production, init_sentry


def get_profile_picture(message: Message) -> Optional[str]:
photos = message.from_user.get_profile_photos()

if photos is not None and photos.total_count > 0:
profile_picture = photos.photos[0][0].get_file()
return profile_picture.file_path


def log_message(message: Message, action: Optional[str] = ''):
async def log_message(message: Message | None, action: str | None = ''):
"""Create a log entry for telegram message"""

if message is None or not DB_ENABLED():
if message is None or not DB_ENABLED() or message.from_user is None:
return
from models import LogEntry

Expand All @@ -33,7 +23,6 @@ def log_message(message: Message, action: Optional[str] = ''):
text=message.text or '',
meta={
'tags': [
*rekognition.get_labels(image_url=get_profile_picture(message)),
*text.Labels(message.text)(),
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Конструкция [*text.Labels(message.text)()] стала выглядеть довольно странно. Почему бы не сделать просто text.Labels(message.text)()?

],
},
Expand All @@ -42,14 +31,12 @@ def log_message(message: Message, action: Optional[str] = ''):
)


def delete(update: Update, context: CallbackContext):
async def delete(update: Update, context: ContextTypes.DEFAULT_TYPE):
message = update.message or update.edited_message

log_message(message, action='delete')
message.bot.delete_message(
message_id=message.message_id,
chat_id=message.chat_id,
)
if message is not None:
await log_message(message, action='delete')
await message.delete()


def delete_messages_that_match(*filters: BaseFilter) -> MessageHandler:
Expand All @@ -66,31 +53,29 @@ def delete_messages_that_match(*filters: BaseFilter) -> MessageHandler:
raise RuntimeError('Please set BOT_TOKEN environment variable')
app_name = os.getenv('BOT_NAME')

bot = Updater(token=bot_token)
dispatcher: Dispatcher = bot.dispatcher # type: ignore
bot = Application.builder().token(bot_token).build()

dispatcher.add_handler(delete_messages_that_match(ContainsTelegramContact()))
dispatcher.add_handler(delete_messages_that_match(ContainsLink()))
dispatcher.add_handler(delete_messages_that_match(IsMessageOnBehalfOfChat()))
dispatcher.add_handler(delete_messages_that_match(ContainsThreeOrMoreEmojies()))
dispatcher.add_handler(delete_messages_that_match(IsMedia()))
bot.add_handler(delete_messages_that_match(ContainsTelegramContact()))
bot.add_handler(delete_messages_that_match(ContainsLink()))
bot.add_handler(delete_messages_that_match(IsMessageOnBehalfOfChat()))
bot.add_handler(delete_messages_that_match(ContainsThreeOrMoreEmojies()))
bot.add_handler(delete_messages_that_match(IsMedia()))

if DB_ENABLED(): # log all not handled messages
from models import create_tables
create_tables() # type: ignore
dispatcher.add_handler(
MessageHandler(filters=Filters.text, callback=lambda update, context: log_message(update.message or update.edited_message)),
bot.add_handler(
MessageHandler(filters=TEXT, callback=lambda update, context: log_message(update.message or update.edited_message)),
)

if in_production():
init_sentry()
da-maltsev marked this conversation as resolved.
Show resolved Hide resolved
bot.start_webhook(
bot.run_webhook(
listen='0.0.0.0',
port=8000,
url_path=bot_token,
webhook_url=f'https://{app_name}.tough-dev.school/' + bot_token,
)
bot.idle()
else: # bot is running on the dev machine
enable_logging()
bot.start_polling()
bot.run_polling()
33 changes: 0 additions & 33 deletions dev-requirements.in

This file was deleted.

Loading