-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
173 lines (135 loc) · 7.42 KB
/
Copy pathapp.py
File metadata and controls
173 lines (135 loc) · 7.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import logging
from datetime import UTC, time
from telegram import Update
from telegram.error import TelegramError
from telegram.ext import (
ApplicationBuilder,
CallbackQueryHandler,
CommandHandler,
ContextTypes,
ConversationHandler,
MessageHandler,
TypeHandler,
filters,
)
import const
from activity_metrics import record_user_activity, refresh_active_user_metrics, start_metrics_server
from admin import Admin
from command import Command
from config import settings
from elastic_sync import sync as sync_elasticsearch
from favorite import Favorite
from omen import Omen
from opinion import Opinion
from poem import Poem
from poet import Poet
from recitation import Recitation
from recitation_uploader.job import run_upload_job
from search import Search
from song import Song
logger = logging.getLogger(__name__)
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Logs handler exceptions and notifies the user that something went wrong."""
logger.error("Exception while handling an update", exc_info=context.error)
if not isinstance(update, Update):
return
try:
if update.callback_query:
await update.callback_query.answer()
if update.effective_chat:
await context.bot.send_message(update.effective_chat.id, const.INTERNAL_ERROR)
except TelegramError:
logger.warning("Failed to notify the user about the error.")
class Application:
def __init__(self, token: str):
self.application = ApplicationBuilder().token(token).concurrent_updates(True).build()
self.application.add_error_handler(error_handler)
if settings.METRICS_ENABLED:
start_metrics_server()
self.add_handlers()
self.add_jobs()
def start_app(self):
if settings.DEBUG:
self.application.run_polling()
else:
self.application.run_webhook(
listen="0.0.0.0",
port=80,
secret_token=settings.WEBHOOK_SECRET_TOKEN,
webhook_url=settings.WEBHOOK_URL,
)
def add_handlers(self):
activity_handler = TypeHandler(Update, record_user_activity)
start_handler = CommandHandler('start', Command.start)
opinion_handler = ConversationHandler(
entry_points=[CommandHandler('opinion', Opinion.opinion)],
states={0: [MessageHandler(filters.ALL & ~filters.Regex(rf'^{const.CANCEL}$'), Opinion.opinion_response)]},
fallbacks=[MessageHandler(filters.Regex(rf'^{const.CANCEL}$'), Opinion.cancel)])
poets_handler = CommandHandler('poets', Poet.poets_menu)
poet_details_handler = CallbackQueryHandler(Poet.poet_details, r'^poet:\d+:\d+$')
category_handler = CallbackQueryHandler(Poem.category_poems, r'^category:\d+:\d+$')
poem_handler = CallbackQueryHandler(Poem.show_poem_by_id, r'^poem:\d+$')
send_to_all_handler = ConversationHandler(entry_points=[CommandHandler('sendtoall', Command.sendtoall)],
states={0: [MessageHandler(filters.TEXT, Admin.send_to_all)]},
fallbacks=[])
recitation_saver_audio_handler = MessageHandler(filters.AUDIO & filters.Chat(settings.OUD_FILES_CHANNEL_ID),
Recitation.add_recitation_file_id_to_db)
search_query_handler = CallbackQueryHandler(Search.search_poems, r'^srch:.+:\d+$')
recitation_handler = CallbackQueryHandler(Recitation.get_recitation_by_id, r'^recitation:\d+$')
favorite_add_handler = CallbackQueryHandler(Favorite.add_to_favorites, r'^favadd:\d+$')
favorite_remove_handler = CallbackQueryHandler(Favorite.remove_from_favorites, r'^favremove:\d+$')
favorite_poems_handler = CommandHandler('favorites', Favorite.list_of_favorite_poems)
favorite_poems_query_handler = CallbackQueryHandler(Favorite.list_of_favorite_poems, r'^favorites:\d+$')
hafez_omen_intro_handler = CommandHandler('omen', Omen.show_omen_introduction)
hafez_show_omen_handler = CallbackQueryHandler(Omen.show_hafez_omen, r'^omen$')
song_saver_data_handler = MessageHandler(filters.TEXT & filters.Chat(settings.OUD_MUSIC_CHANNEL_ID),
Song.add_song_data_to_db)
song_saver_audio_handler = MessageHandler(filters.AUDIO & filters.Chat(settings.OUD_MUSIC_CHANNEL_ID),
Song.add_song_file_id_to_db)
song_handler = CallbackQueryHandler(Song.get_song_by_id, r'^song:\d+$')
recitations_handler = CallbackQueryHandler(Recitation.show_recitations, r'^recitations:\d+$')
songs_handler = CallbackQueryHandler(Song.show_songs, r'^songs:\d+$')
reply_opinion_handler = ConversationHandler(
entry_points=[MessageHandler(filters.Regex(r'^/reply_\d+_\d+$'), Opinion.save_user_info)],
states={0: [MessageHandler(filters.ALL & ~filters.Regex(rf'^{const.CANCEL}$'), Opinion.reply_to_opinion)]},
fallbacks=[MessageHandler(filters.Regex(rf'^{const.CANCEL}$'), Opinion.cancel)])
search_title_query_handler = CallbackQueryHandler(Search.search_title, r'^st:.+:\d+$')
commands_handler = MessageHandler(filters.COMMAND, Command.general_command)
search_message_handler = ConversationHandler(
entry_points=[MessageHandler(filters.TEXT, Search.search_destination)],
states={
0: [
MessageHandler(filters.Regex(rf"^{const.SEARCH_POET}$"), Search.search_poet),
MessageHandler(filters.Regex(rf"^{const.SEARCH_VERSE}$"), Search.search_poems),
MessageHandler(filters.Regex(rf"^{const.SEARCH_POEM_TITLE}$"), Search.search_title),
MessageHandler(filters.ALL, Search.cancel)
]
},
fallbacks=[MessageHandler(filters.Regex(rf"^{const.CANCEL}$"), Search.cancel)]
)
self.application.add_handler(activity_handler, group=-1)
self.application.add_handlers(
[start_handler, opinion_handler, poets_handler, poet_details_handler, category_handler, poem_handler,
send_to_all_handler, recitation_saver_audio_handler, search_query_handler, recitation_handler,
favorite_add_handler, favorite_remove_handler, favorite_poems_handler, favorite_poems_query_handler,
hafez_omen_intro_handler, hafez_show_omen_handler, song_saver_data_handler, song_saver_audio_handler,
song_handler, recitations_handler, songs_handler, reply_opinion_handler, search_title_query_handler,
commands_handler, search_message_handler])
def add_jobs(self) -> None:
self.application.job_queue.run_daily(
sync_elasticsearch,
time=time(hour=2, minute=0, tzinfo=UTC),
name="daily_elasticsearch_sync",
)
if settings.RECITATION_UPLOAD_ENABLED:
self.application.job_queue.run_daily(
run_upload_job,
time=time(hour=1, minute=0, tzinfo=UTC),
name="daily_recitation_upload",
)
if settings.METRICS_ENABLED:
self.application.job_queue.run_repeating(
refresh_active_user_metrics,
interval=settings.ACTIVE_USERS_REFRESH_INTERVAL_SECONDS,
name="active_users_metrics_refresh",
)