-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
1787 lines (1509 loc) · 68.7 KB
/
bot.py
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import subprocess
import nest_asyncio
import re
import json
import os
import sqlite3
import re
import logging
import requests
import aiohttp
import telegram.error
from datetime import datetime
from zoneinfo import ZoneInfo
from sqlite3 import Error
from telegram.constants import ChatAction
from telegram import (
Update,
InlineKeyboardButton,
InlineKeyboardMarkup,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from telegram.ext import (
ApplicationBuilder,
CommandHandler,
MessageHandler,
filters,
CallbackQueryHandler,
ContextTypes,
)
import sys
import threading
# Configurations
CONFIG_DIR = "config"
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
DATABASE_DIR = "database"
DATABASE_FILE = os.path.join(DATABASE_DIR, "group_data.db")
# Check if config.json is present
if not os.path.isfile(CONFIG_FILE):
print(
f"ERROR: '{CONFIG_FILE}' not found. Please create the configuration file before starting the bot."
)
sys.exit(1) # Exit with status code 1
# Function to redact sensitive information like tokens and API keys
def redact_sensitive_info(value, visible_chars=4):
if isinstance(value, str) and len(value) > visible_chars * 2:
return f"{value[:visible_chars]}{'*' * (len(value) - visible_chars * 2)}{value[-visible_chars:]}"
return value
# Load the config file
with open(CONFIG_FILE, "r") as config_file:
config = json.load(config_file)
# BOT
TOKEN = config.get("bot").get("TOKEN")
TIMEZONE = config.get("bot").get("TIMEZONE", "Europe/Berlin")
LOG_LEVEL = config.get("bot").get("LOG_LEVEL", "INFO").upper()
# WELCOME
IMAGE_URL = config.get("welcome").get("IMAGE_URL")
BUTTON_URL = config.get("welcome").get("BUTTON_URL")
SUPPORT_URL = config.get("welcome").get("SUPPORT_URL")
# NIGHTMODE
NIGHTMODE_START = config.get("nightmode").get("NIGHTMODE_START")
NIGHTMODE_END = config.get("nightmode").get("NIGHTMODE_END")
# TMDB
TMDB_API_KEY = config.get("tmdb").get("API_KEY")
DEFAULT_LANGUAGE = config.get("tmdb").get("DEFAULT_LANGUAGE")
# SONARR
SONARR_URL = config.get("sonarr").get("URL")
SONARR_API_KEY = config.get("sonarr").get("API_KEY")
SONARR_QUALITY_PROFILE_NAME = config.get("sonarr").get("QUALITY_PROFILE_NAME")
SONARR_ROOT_FOLDER_PATH = config.get("sonarr").get("ROOT_FOLDER_PATH")
# RADARR
RADARR_URL = config.get("radarr").get("URL")
RADARR_API_KEY = config.get("radarr").get("API_KEY")
RADARR_QUALITY_PROFILE_NAME = config.get("radarr").get("QUALITY_PROFILE_NAME")
RADARR_ROOT_FOLDER_PATH = config.get("radarr").get("ROOT_FOLDER_PATH")
# COMMANDS
START_COMMAND = config.get("commands").get("START", "start")
WELCOME_COMMAND = config.get("commands").get("WELCOME", "welcome")
NIGHT_MODE_ENABLE_COMMAND = config.get("commands").get(
"NIGHT_MODE_ENABLE", "enable_night_mode"
)
NIGHT_MODE_DISABLE_COMMAND = config.get("commands").get(
"NIGHT_MODE_DISABLE", "disable_night_mode"
)
TMDB_LANGUAGE_COMMAND = config.get("commands").get("TMDB_LANGUAGE", "set_language")
SET_GROUP_ID_COMMAND = config.get("commands").get("SET_GROUP_ID", "set_group_id")
HELP_COMMAND = config.get("commands").get("HELP", "help")
SEARCH_COMMAND = config.get("commands").get("SEARCH", "search")
# TOPICS
TOPICS = config.get("topics", {})
# Configure the bot logger
logger = logging.getLogger("bot")
# Configure APScheduler logger to suppress INFO logs
apscheduler_logger = logging.getLogger("apscheduler")
apscheduler_logger.setLevel(
logging.WARNING
) # Set it to WARNING or ERROR to suppress INFO logs
# Existing basic configuration for the bot logs
logging.basicConfig(
format="[%(asctime)s] [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=getattr(logging, "LOG_LEVEL", logging.INFO), # Use appropriate log level
)
# Create an asyncio lock for sequential logging
log_lock = asyncio.Lock()
# Global reference for Django process and bot application
django_process = None
application = None
# Global reference for the group data
GROUP_CHAT_ID = None
LANGUAGE = None
# Global variable to track if night mode is active
night_mode_lock = asyncio.Lock()
task_lock = asyncio.Lock()
# Start Django server in a background thread
def start_django_server():
global django_process
try:
# Step 1: Run makemigrations
logger.info("Running makemigrations...")
subprocess.run(
[sys.executable, "panel/manage.py", "makemigrations", "--noinput"],
check=True,
)
logger.info("Makemigrations completed.")
# Step 2: Run migrate
logger.info("Running migrate...")
subprocess.run([sys.executable, "panel/manage.py", "migrate"], check=True)
logger.info("Migrations applied successfully.")
# Step 3: Run collectstatic
logger.info("Running collectstatic...")
subprocess.run(
[sys.executable, "panel/manage.py", "collectstatic", "--noinput"],
check=True,
)
logger.info("Static files collected.")
# Step 4: Run the Django server
logger.info("Starting Django server...")
command = [sys.executable, "panel/manage.py", "runserver", "0.0.0.0:8000"]
django_process = subprocess.Popen(command)
logger.info("Django server started.")
except subprocess.CalledProcessError as e:
logger.error(f"Command '{e.cmd}' failed with exit code {e.returncode}")
except Exception as e:
logger.error(f"Failed to start Django server: {e}")
# Stop Django server
def stop_django_server():
global django_process
if django_process is not None:
django_process.terminate()
django_process.wait()
logger.info("Django server stopped.")
# Function to load version and author info from a file
def load_version_info(file_path):
version_info = {}
try:
with open(file_path, "r") as file:
for line in file:
key, value = line.strip().split(
": ", 1
) # Split on first colon and space
version_info[key] = value
except Exception as e:
logger.error(f"Failed to load VERSION INFO: {e}")
return version_info
# Function to check and log paths
def check_and_log_paths():
# Check if config directory exists
logger.info("=====================================================")
logger.info("Checking Directories.....")
logger.info("-----------")
if not os.path.exists(CONFIG_DIR):
os.makedirs(CONFIG_DIR)
logger.info("")
logger.warning(f"CONFIG directory '{CONFIG_DIR}' not found.")
logger.info(f"Creating CONFIG directory....")
logger.info(f"CONFIG directory '{CONFIG_DIR}' created.")
logger.info("")
else:
logger.info(f"CONFIG directory '{CONFIG_DIR}' already exists.")
# Check if database directory exists
if not os.path.exists(DATABASE_DIR):
os.makedirs(DATABASE_DIR)
logger.info("")
logger.warning(f"DATABASE directory '{DATABASE_DIR}' not found.")
logger.info(f"Creating DATABASE directory....")
logger.info(f"DATABASE directory '{DATABASE_DIR}' created.")
logger.info("")
else:
logger.info(f"DATABASE directory '{DATABASE_DIR}' already exists.")
# Check if database file exists
if not os.path.exists(DATABASE_FILE):
logger.warning(
f"DATABASE FILE '{DATABASE_FILE}' does not exist. It will be created automatically."
)
else:
logger.info(f"DATABASE FILE '{DATABASE_FILE}' already exists.")
# Database initialization
def init_db():
try:
if not os.path.exists(DATABASE_DIR):
os.makedirs(DATABASE_DIR)
with sqlite3.connect(DATABASE_FILE) as conn:
cursor = conn.cursor()
# Create the tables with the timezone column
cursor.execute(
"""CREATE TABLE IF NOT EXISTS group_data (
id INTEGER PRIMARY KEY,
group_chat_id INTEGER,
group_name TEXT,
message_id INTEGER,
user_id INTEGER,
night_mode_message_id INTEGER,
night_mode_active BOOLEAN DEFAULT 0,
language TEXT
)"""
)
# Get the default language
default_language = config.get("tmdb", {}).get(
"DEFAULT_LANGUAGE", "en"
) # Provide a fallback default
# Check if the table is empty and set the default language, group name, and timezone
cursor.execute("SELECT COUNT(*) FROM group_data")
count = cursor.fetchone()[0]
if count == 0: # Only insert if the table is empty
cursor.execute(
"""INSERT INTO group_data (group_chat_id, group_name, language, night_mode_active) VALUES (?, ?, ?, ?)""",
(None, "Default Group", default_language, False),
)
conn.commit()
logger.info("Database initialized.")
except Error as e:
logger.error(f"An error occurred: {e}")
# Log all config entries, redacting sensitive information
def log_config_entries(config):
sensitive_keys = ["TOKEN", "API_KEY", "SECRET", "KEY"] # Keys to redact
logger.info("Current Config.json settings:")
logger.info("-----------")
for section, entries in config.items():
if isinstance(entries, dict):
logger.info(f"Section [{section}]:")
for key, value in entries.items():
if any(
sensitive_key in key.upper() for sensitive_key in sensitive_keys
):
value = redact_sensitive_info(value)
logger.info(f" {key}: {value}")
else:
logger.info(f"{section}: {entries}")
logger.info("=====================================================")
def configure_bot(TOKEN, TIMEZONE="Europe/Berlin"):
logger.info("=====================================================")
logger.info("Checking Globals....")
logger.info("-----------")
# Log the successful retrieval of the token with only the first and last 4 characters visible
if TOKEN:
redacted_token = redact_sensitive_info(TOKEN)
logger.info(f"TOKEN retrieved: '{redacted_token}'")
else:
logger.error(f"Failed to retrieve BOT TOKEN from config. <-----")
raise ValueError("BOT TOKEN is missing or invalid.")
# Timezone configuration
try:
TIMEZONE_OBJ = ZoneInfo(TIMEZONE)
logger.info(f"TIMEZONE is set to '{TIMEZONE}'.")
except Exception as e:
logger.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
logger.error(f"Invalid TIMEZONE '{TIMEZONE}' in config.json <-----")
logger.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
logger.info(f"Defaulting TIMEZONE to 'Europe/Berlin'. Error: {e}")
TIMEZONE_OBJ = ZoneInfo("Europe/Berlin")
return TIMEZONE_OBJ
# Save group chat ID and language to database
def save_group_data(group_chat_id, group_name, language):
with sqlite3.connect(DATABASE_FILE) as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT OR REPLACE INTO group_data (id, group_chat_id, group_name, language) VALUES (1, ?, ?, ?)",
(group_chat_id, group_name, language),
)
conn.commit()
# Load group chat ID and language from database
def load_group_data():
with sqlite3.connect(DATABASE_FILE) as conn:
cursor = conn.cursor()
cursor.execute("SELECT group_chat_id, language FROM group_data WHERE id=1")
row = cursor.fetchone()
if row:
return row[0], row[1]
return None, DEFAULT_LANGUAGE
LANGUAGE = DEFAULT_LANGUAGE
# Check group data in database
def initialize_group_data():
global GROUP_CHAT_ID, LANGUAGE
group_chat_id, language = load_group_data()
GROUP_CHAT_ID = group_chat_id # Only assign the chat ID
LANGUAGE = language
if GROUP_CHAT_ID is None:
logger.info("")
logger.warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
logger.warning("Missing GROUP CHAT ID....")
logger.warning("GROUP CHAT ID is needed for NIGHT MODE")
logger.warning("Please set it using '/set_group_id' <-----")
logger.warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
logger.info("")
logger.info(f"TMDb LANGUAGE is set to: '{LANGUAGE}'")
else:
logger.info(f"GROUP CHAT ID is set to: '{GROUP_CHAT_ID}'")
logger.info(f"TMDb LANGUAGE is set to: '{LANGUAGE}'")
# Load group name
def get_group_name(group_chat_id):
with sqlite3.connect(DATABASE_FILE) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT group_name FROM group_data WHERE group_chat_id = ?",
(group_chat_id,),
)
row = cursor.fetchone()
return row[0] if row else "Unknown Group"
# Save night mode message ID to database
def update_night_mode_message_id(group_chat_id, message_id):
with sqlite3.connect(DATABASE_FILE) as conn:
cursor = conn.cursor()
try:
cursor.execute(
"""UPDATE group_data SET night_mode_message_id = ? WHERE group_chat_id = ?""",
(message_id, group_chat_id),
)
conn.commit()
logger.info(
f"Updated NIGHT MODE MESSAGE ID to {message_id} for GROUP CHAT ID: {group_chat_id}."
)
except Exception as e:
logger.error(
f"Failed to update NIGHT MODE MESSAGE ID for GROUP CHAT ID: {group_chat_id}. Error: {e}"
)
def get_night_mode_info(group_chat_id):
with sqlite3.connect(DATABASE_FILE) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT night_mode_message_id, night_mode_active FROM group_data WHERE group_chat_id = ?",
(group_chat_id,),
)
row = cursor.fetchone()
return row if row else (None, False) # Return None and False if not found
# Timezone configuration
try:
TIMEZONE_OBJ = ZoneInfo(TIMEZONE)
except Exception as e:
TIMEZONE_OBJ = ZoneInfo("Europe/Berlin")
# Get the current time in the desired timezone
def get_current_time():
return datetime.now(TIMEZONE_OBJ)
# Avoid issues with special characters in MarkdownV2
# Function to escape special characters for MarkdownV2
def escape_markdown_v2(text):
escape_chars = r"([_*\[\]()~`>#+\-=|{}.!])"
return re.sub(escape_chars, r"\\\1", text)
# Convert the rating to a 10-star scale
def rating_to_stars(rating):
stars = (rating / 10) * 10
# Determine the number of full stars, half stars, and empty stars
full_stars = int(stars) # Full stars
half_star = 1 if stars - full_stars >= 0.5 else 0 # Half star
empty_stars = 10 - full_stars - half_star # Empty stars
# Build the star emoji string
star_display = "⭐" * full_stars + "✨" * half_star + "★" * empty_stars
return star_display
def extract_year_from_input(selected_title):
# Use regex to find a year in parentheses, even if the parentheses are incomplete
match = re.search(r"\((\d{4})", selected_title)
if match:
# Ensure the closing parenthesis is present and return the title up to the year
return f"{selected_title[:match.end()]})"
return selected_title # If no year is found, return the original title
# Search for a movie or TV show using TMDB API with multiple results handling
async def search_media(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
if not context.args:
await update.message.reply_text(
"Bitte ergänze den Befehl mit einem Film oder Serien Titel (e.g., /search Inception)."
)
return
title = " ".join(context.args)
logger.info(f"Searching for media: {title}")
# Show the typing indicator while the bot is working
await context.bot.send_chat_action(
chat_id=update.effective_chat.id, action=ChatAction.TYPING
)
await asyncio.sleep(
0.5
) # Small delay to make sure the typing action is visible
# Send a progress message
status_message = await update.message.reply_text(
"🔍 Suche nach Ergebnissen, bitte warten...."
)
# Actual processing logic (searching media)
url = f"https://api.themoviedb.org/3/search/multi?api_key={TMDB_API_KEY}&query={title}&language={LANGUAGE}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 429:
retry_after = int(response.headers.get("Retry-After", 1))
logger.warning(
f"Rate limited by TMDb. Retrying after {retry_after} seconds."
)
await asyncio.sleep(retry_after)
async with session.get(url) as retry_response:
media_data = await retry_response.json()
else:
media_data = await response.json()
if not media_data["results"]:
await status_message.edit_text(
text=f"🛑 Keine Ergebnisse gefunden für *{title}*. Bitte versuche einen anderen Titel.",
parse_mode="Markdown",
)
return
# If more than one result is found, show a list to the user
if len(media_data["results"]) > 1:
media_titles = []
keyboard = []
for i, media in enumerate(media_data["results"]):
media_type = media["media_type"]
media_title = media["title"] if media_type == "movie" else media["name"]
release_date = media.get(
"release_date", media.get("first_air_date", "N/A")
)
release_year = release_date[:4] if release_date != "N/A" else "N/A"
# Use the index to generate callback data for InlineKeyboard
media_titles.append(f"{media_title} ({release_year})")
keyboard.append(
[
InlineKeyboardButton(
f"{media_title} ({release_year})",
callback_data=f"select_media_{i}",
)
]
)
# Create the InlineKeyboardMarkup with the list of results
reply_markup = InlineKeyboardMarkup(keyboard)
await status_message.edit_text(
"Mehrere Ergebnisse gefunden, bitte wähle den richtigen Film oder Serie aus:",
reply_markup=reply_markup,
)
# Store media results in user data for later selection
context.user_data["media_options"] = media_data["results"]
logger.info(f"Media options stored: {len(media_data['results'])} results")
return
# If only one result, continue with displaying details and confirmation
media = media_data["results"][0]
await handle_media_selection(update, context, media)
except aiohttp.ClientError as http_err:
logger.error(f"HTTP error occurred: {http_err}")
await status_message.edit_text(
"🛑 Ein HTTP Fehler ist beim laden der Metadaten von TMDB aufgetreten. Bitte versuche es später erneut."
)
except Exception as e:
logger.error(f"An unexpected error occurred: {e}")
await status_message.edit_text(
"🛑 Ein unerwarteter Fehler ist aufgetreten. Bitte versuche es später erneut."
)
# Function to fetch additional details of the movie/TV show from TMDb
async def fetch_media_details(media_type, media_id):
url = f"https://api.themoviedb.org/3/{media_type}/{media_id}?api_key={TMDB_API_KEY}&language={LANGUAGE}"
logger.info(f"Fetching details from URL: {url}")
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
media_details = await response.json()
logger.info(f"Details fetched successfully for media_id: {media_id}")
return media_details
# Function to check if the series is already in Sonarr
async def check_series_in_sonarr(series_tvdb_id):
try:
async with aiohttp.ClientSession() as session:
async with session.get(
f"{SONARR_URL}/api/v3/series", params={"apikey": SONARR_API_KEY}
) as response:
series_list = await response.json()
for series in series_list:
if series["tvdbId"] == series_tvdb_id:
logger.info(
f"Series '{series['title']}' already exists in Sonarr (TVDB ID: {series['tvdbId']})"
)
return True
return False
except aiohttp.ClientError as http_err:
logger.error(f"HTTP error while checking Sonarr: {http_err}")
return False
except Exception as e:
logger.error(f"Unexpected error while checking Sonarr: {e}")
return False
# Function to check if the movie is already in Radarr
async def check_movie_in_radarr(movie_tmdb_id):
try:
async with aiohttp.ClientSession() as session:
async with session.get(
f"{RADARR_URL}/api/v3/movie", params={"apikey": RADARR_API_KEY}
) as response:
movie_list = await response.json()
for movie in movie_list:
if movie["tmdbId"] == movie_tmdb_id:
logger.info(f"Movie '{movie['title']}' already exists in Radarr.")
return True
return False
except aiohttp.ClientError as http_err:
logger.error(f"HTTP error while checking Radarr: {http_err}")
return False
except Exception as e:
logger.error(f"Unexpected error while checking Radarr: {e}")
return False
# Function to get quality profile ID by name from Sonarr
async def get_quality_profile_id(sonarr_url, api_key, profile_name):
try:
response = requests.get(
f"{sonarr_url}/api/v3/qualityprofile", params={"apikey": api_key}
)
response.raise_for_status()
profiles = response.json()
for profile in profiles:
if profile["name"] == profile_name:
return profile["id"]
logger.warning(f"Quality profile '{profile_name}' not found in Sonarr.")
return None
except requests.exceptions.HTTPError as http_err:
logger.error(f"HTTP error occurred while fetching quality profiles: {http_err}")
return None
except Exception as e:
logger.error(f"An unexpected error occurred: {e}")
return None
# Function to add a series to Sonarr
async def add_series_to_sonarr(
series_name, update: Update, context: ContextTypes.DEFAULT_TYPE
):
# Show typing indicator while adding the series
await context.bot.send_chat_action(
chat_id=update.effective_chat.id, action=ChatAction.TYPING
)
await asyncio.sleep(0.5) # Small delay to make sure the typing action is visible
# Determine where to send the status message (handling both update.message and update.callback_query)
if update.message:
status_message = await update.message.reply_text(
"🎬 Serien Anfrage läuft, bitte warten..."
)
else:
status_message = await update.callback_query.message.reply_text(
"🎬 Serien Anfrage läuft, bitte warten..."
)
# First, get the TMDb ID for the series
tmdb_url = f"https://api.themoviedb.org/3/search/tv?api_key={TMDB_API_KEY}&query={series_name}"
async with aiohttp.ClientSession() as session:
async with session.get(tmdb_url) as tmdb_response:
tmdb_data = await tmdb_response.json()
if not tmdb_data["results"]:
logger.error(f"No TMDb results found for the series '{series_name}'")
await status_message.edit_text(
f"🛑 Keine TMDB Ergebnisse für die Serie *{series_name}* gefunden.",
parse_mode="Markdown",
)
return
# Use the first search result for simplicity
series_tmdb_id = tmdb_data["results"][0]["id"]
# Use TMDb ID to get TVDB ID (Sonarr uses TVDB)
external_ids_url = f"https://api.themoviedb.org/3/tv/{series_tmdb_id}/external_ids?api_key={TMDB_API_KEY}"
async with aiohttp.ClientSession() as session:
async with session.get(external_ids_url) as external_ids_response:
external_ids_data = await external_ids_response.json()
tvdb_id = external_ids_data.get("tvdb_id")
if not tvdb_id:
logger.error(f"No TVDB ID found for the series '{series_name}'")
await status_message.edit_text(
f"🛑 Keine TVDB ID für die Serie *{series_name}* gefunden.",
parse_mode="Markdown",
)
return
# Check if the series is already in Sonarr
if await check_series_in_sonarr(tvdb_id):
logger.info(
f"Series '{series_name}' already exists in Sonarr, skipping addition."
)
await status_message.edit_text(
f"✅ Die Serie *{series_name}* ist bereits bei StreamNet TV vorhanden.",
parse_mode="Markdown",
)
return
# Proceed with adding the series if it's not found in Sonarr
quality_profile_id = await get_quality_profile_id(
SONARR_URL, SONARR_API_KEY, SONARR_QUALITY_PROFILE_NAME
)
if quality_profile_id is None:
logger.error("Quality profile not found in Sonarr.")
await status_message.edit_text("🛑 Quality Profil in Sonarr nicht gefunden.")
return
data = {
"title": series_name,
"qualityProfileId": quality_profile_id,
"rootFolderPath": SONARR_ROOT_FOLDER_PATH,
"seasonFolder": True,
"tvdbId": tvdb_id,
"monitored": True,
"addOptions": {
"searchForMissingEpisodes": True # Attempt to trigger search via addOptions
},
}
async with aiohttp.ClientSession() as session:
async with session.post(
f"{SONARR_URL}/api/v3/series", json=data, params={"apikey": SONARR_API_KEY}
) as response:
if response.status == 201:
logger.info(f"Series '{series_name}' added to Sonarr successfully.")
series_id = (await response.json()).get("id")
if (
not (await response.json())
.get("addOptions", {})
.get("searchForMissingEpisodes", False)
):
logger.info(f"Triggering manual search for series '{series_name}'.")
search_data = {"name": "SeriesSearch", "seriesId": series_id}
async with session.post(
f"{SONARR_URL}/api/v3/command",
json=search_data,
params={"apikey": SONARR_API_KEY},
) as search_response:
if search_response.status == 201:
logger.info(
f"Manual search for series '{series_name}' started."
)
await status_message.edit_text(
f"✅ Die Serie *{series_name}* wurde angefragt. Manuelle Suche wurde gestartet.",
parse_mode="Markdown",
)
else:
logger.error(
f"Failed to start manual search for series '{series_name}'. Status code: {search_response.status_code}"
)
await status_message.edit_text(
f"🛑 Suche für die Serie *{series_name}* gescheitert.",
parse_mode="Markdown",
)
else:
logger.info(
f"Search for series '{series_name}' started automatically."
)
await status_message.edit_text(
f"✅ Die Serie *{series_name}* wurde angefragt und die Suche wurde gestartet.",
parse_mode="Markdown",
)
else:
logger.error(
f"Failed to add series '{series_name}' to Sonarr. Status code: {response.status}"
)
await status_message.edit_text(
f"🛑 Anfragen der Serie *{series_name}* gescheitert.\nStatus code: *{response.status_code}*",
parse_mode="Markdown",
)
# Function to get quality profile ID by name from Radarr
async def get_radarr_quality_profile_id(radarr_url, api_key, profile_name):
try:
response = requests.get(
f"{radarr_url}/api/v3/qualityprofile", params={"apikey": api_key}
)
response.raise_for_status() # Raise an error for bad responses
profiles = response.json()
for profile in profiles:
if profile["name"] == profile_name:
return profile["id"]
logger.warning(f"Quality profile '{profile_name}' not found in Radarr.")
return None
except requests.exceptions.HTTPError as http_err:
logger.error(f"HTTP error occurred while fetching quality profiles: {http_err}")
return None
except Exception as e:
logger.error(f"An unexpected error occurred: {e}")
return None
# Function to add a movie to Radarr
async def add_movie_to_radarr(
movie_name, update: Update, context: ContextTypes.DEFAULT_TYPE
):
# Show typing indicator while adding the movie
await context.bot.send_chat_action(
chat_id=update.effective_chat.id, action=ChatAction.TYPING
)
await asyncio.sleep(0.5) # Small delay to make sure the typing action is visible
# Determine where to send the status message (handling both update.message and update.callback_query)
if update.message:
status_message = await update.message.reply_text(
"🎬 Film Anfrage läuft, bitte warten..."
)
else:
status_message = await update.callback_query.message.reply_text(
"🎬 Film Anfrage läuft, bitte warten..."
)
# First, get the TMDb ID for the movie
tmdb_url = f"https://api.themoviedb.org/3/search/movie?api_key={TMDB_API_KEY}&query={movie_name}"
async with aiohttp.ClientSession() as session:
async with session.get(tmdb_url) as tmdb_response:
tmdb_data = await tmdb_response.json()
if not tmdb_data["results"]:
logger.error(f"No TMDb results found for the movie '{movie_name}'")
await status_message.edit_text(
f"🛑 Keine TMDB Ergebnisse für den Film *{movie_name}* gefunden.",
parse_mode="Markdown",
)
return
# Use the first search result for simplicity
movie_tmdb_id = tmdb_data["results"][0]["id"]
# Check if the movie is already in Radarr
if await check_movie_in_radarr(movie_tmdb_id):
logger.info(
f"Movie '{movie_name}' already exists in Radarr, skipping addition."
)
await status_message.edit_text(
f"✅ Der Film *{movie_name}* ist bereits bei StreamNet TV vorhanden.",
parse_mode="Markdown",
)
return
# Proceed with adding the movie if it's not found in Radarr
quality_profile_id = await get_radarr_quality_profile_id(
RADARR_URL, RADARR_API_KEY, RADARR_QUALITY_PROFILE_NAME
)
if quality_profile_id is None:
logger.error("Quality profile not found in Radarr.")
await status_message.edit_text("🛑 Quality Profil in Radarr nicht gefunden.")
return
data = {
"title": movie_name,
"qualityProfileId": quality_profile_id,
"rootFolderPath": RADARR_ROOT_FOLDER_PATH,
"tmdbId": movie_tmdb_id,
"monitored": True,
"addOptions": {
"searchForMovie": True # Attempt to trigger search via addOptions
},
}
async with aiohttp.ClientSession() as session:
async with session.post(
f"{RADARR_URL}/api/v3/movie", json=data, params={"apikey": RADARR_API_KEY}
) as response:
if response.status == 201:
logger.info(f"Movie '{movie_name}' added to Radarr successfully.")
movie_id = (await response.json()).get("id")
if (
not (await response.json())
.get("addOptions", {})
.get("searchForMovie", False)
):
logger.info(f"Triggering manual search for movie '{movie_name}'.")
search_data = {"name": "MoviesSearch", "movieIds": [movie_id]}
async with session.post(
f"{RADARR_URL}/api/v3/command",
json=search_data,
params={"apikey": RADARR_API_KEY},
) as search_response:
if search_response.status == 201:
logger.info(
f"Manual search for movie '{movie_name}' started."
)
await status_message.edit_text(
f"✅ Der Film *{movie_name}* wurde angefragt. Manuelle Suche wurde gestartet.",
parse_mode="Markdown",
)
else:
logger.error(
f"Failed to start manual search for movie '{movie_name}'. Status code: {search_response.status_code}"
)
await status_message.edit_text(
f"🛑 Suche für den Film *{movie_name}* gescheitert.",
parse_mode="Markdown",
)
else:
logger.info(
f"Search for movie '{movie_name}' started automatically."
)
await status_message.edit_text(
f"✅ Der Film *{movie_name}* wurde angefragt und die Suche wurde gestartet.",
parse_mode="Markdown",
)
else:
logger.error(
f"Failed to add movie '{movie_name}' to Radarr. Status code: {response.status}"
)
await status_message.edit_text(
f"🛑 Anfragen des Films *{movie_name}* gescheitert.\nStatus code: *{response.status_code}*",
parse_mode="Markdown",
)
# Handle the user's media selection and display media details before confirming
async def handle_media_selection(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.callback_query is None:
await update.message.reply_text("Ungültige Auswahl. Bitte versuche es erneut.")
logger.error("No callback query found in the update.")
return
# Proceed with the rest of your existing logic
media = context.user_data.get("selected_media")
if not media:
await update.callback_query.message.reply_text(
"Ungültige Auswahl. Bitte versuche es erneut."
)
logger.error("No selected media found in user data.")
return
# Show the typing indicator while the bot is working
await context.bot.send_chat_action(
chat_id=update.effective_chat.id, action=ChatAction.TYPING
)
await asyncio.sleep(0.5) # Small delay to make sure the typing action is visible
# Send a progress message
status_message = await update.callback_query.message.reply_text(
"📄 Metadaten werden geladen, bitte warten..."
)
media_title = media["title"] if media["media_type"] == "movie" else media["name"]
media_type = media["media_type"]
media_id = media["id"]
# Fetch additional media details from TMDb
try:
media_details = await fetch_media_details(media_type, media_id)
logger.info(f"Fetched media details for {media_title} (TMDb ID: {media_id})")
except Exception as e:
await status_message.edit_text(
"Fehler beim Laden der Metadaten. Bitte versuche es später erneut."
)
logger.error(f"Failed to fetch media details: {e}")
return
# Convert rating to stars using the helper function
rating = media_details.get("vote_average", 0)
star_rating = rating_to_stars(rating)
# Extract the year from the release date for the detailed message as well
full_release_date = media_details.get(
"release_date", media_details.get("first_air_date", "N/A")
)
release_year_detailed = (
full_release_date[:4] if full_release_date != "N/A" else "N/A"
)
# Generate the TMDb URL
tmdb_url = f"https://www.themoviedb.org/{'movie' if media_type == 'movie' else 'tv'}/{media_id}"
# Prepare the message with media details, star rating, and the TMDb URL
message = (
f"🎬 *{media_title}* ({release_year_detailed}) \n\n"
f"{star_rating} - {rating}/10\n\n"
f"{media_details.get('overview', 'No summary available.')}\n\n"
f"[Weitere Infos bei TMDb]({tmdb_url})" # Adding the TMDb URL link at the bottom
)
# Send media details regardless of existence in Sonarr/Radarr
if media_details.get("poster_path"):
poster_url = f"https://image.tmdb.org/t/p/w500{media_details['poster_path']}"
await status_message.edit_text(
text="🎬 Metadaten geladen!", parse_mode="Markdown"
)
await update.callback_query.message.reply_photo(
photo=poster_url, caption=message, parse_mode="Markdown"
)
else:
await status_message.edit_text(text=message, parse_mode="Markdown")
# Now check if the media already exists in Radarr or Sonarr