-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram_bot.py
309 lines (252 loc) · 10.4 KB
/
telegram_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
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
TELEGRAM_API_TOKEN = os.getenv('TELEGRAM_API_TOKEN')
EMBY_API_KEY = os.getenv('EMBY_API_KEY')
JELLYFIN_API_KEY = os.getenv('JELLYFIN_API_KEY')
JELLYSEERR_API_KEY = os.getenv('JELLYSEERR_API_KEY')
EMBY_URL = os.getenv('EMBY_URL')
JELLYFIN_URL = os.getenv('JELLYFIN_URL')
JELLYSEERR_URL = os.getenv('JELLYSEERR_URL')
SETTINGS_USER = os.getenv('SETTINGS_USER', 'settings') # Default to 'settings' if not set
AUTHORIZED_USERS = list(map(int, os.getenv('AUTHORIZED_USERS', '').split(',')))
# Function to check if the user is authorized
def is_authorized(user_id):
print(f"User ID: {user_id}") # This will print the user ID to your console or logs
return user_id in AUTHORIZED_USERS
# Command to add multiple users
async def add_user(update: Update, context):
if not is_authorized(update.message.from_user.id):
await update.message.reply_text("You are not authorized to use this bot.")
return
if len(context.args) < 1:
await update.message.reply_text("Usage: /adduser username1 username2 ...")
return
usernames = context.args
emby_success = []
jellyfin_success = []
jellyseerr_success = []
for username in usernames:
password = username # Automatically use the username as the password
emby_result = jellyfin_result = jellyseerr_result = True
if EMBY_API_KEY and EMBY_URL:
try:
emby_result = await create_emby_user(username, password)
if emby_result:
emby_success.append(username)
except Exception as e:
emby_result = False
if JELLYFIN_API_KEY and JELLYFIN_URL:
try:
jellyfin_result = await create_jellyfin_user(username, password)
if jellyfin_result:
jellyfin_success.append(username)
except Exception as e:
jellyfin_result = False
if JELLYSEERR_API_KEY and JELLYSEERR_URL and jellyfin_result:
try:
jellyseerr_result = await import_jellyfin_users_to_jellyseerr(username)
if jellyseerr_result:
jellyseerr_success.append(username)
except Exception as e:
jellyseerr_result = False
messages = []
if emby_success:
messages.append(f"Following Emby users created successfully:\n{' '.join(emby_success)}")
if jellyfin_success:
messages.append(f"Following Jellyfin users created successfully:\n{' '.join(jellyfin_success)}")
if jellyseerr_success:
messages.append(f"Following Jellyseerr users imported successfully:\n{' '.join(jellyseerr_success)}")
await update.message.reply_text("\n".join(messages))
# Command to delete multiple users
async def del_user(update: Update, context):
if not is_authorized(update.message.from_user.id):
await update.message.reply_text("You are not authorized to use this bot.")
return
if len(context.args) < 1:
await update.message.reply_text("Usage: /deluser username1 username2 ...")
return
usernames = context.args
emby_success = []
jellyfin_success = []
jellyseerr_success = []
for username in usernames:
emby_result = jellyfin_result = jellyseerr_result = True
if EMBY_API_KEY and EMBY_URL:
try:
emby_result = await delete_emby_user(username)
if emby_result:
emby_success.append(username)
except Exception as e:
emby_result = False
if JELLYFIN_API_KEY and JELLYFIN_URL:
try:
jellyfin_result = await delete_jellyfin_user(username)
if jellyfin_result:
jellyfin_success.append(username)
except Exception as e:
jellyfin_result = False
if JELLYSEERR_API_KEY and JELLYSEERR_URL:
try:
jellyseerr_result = await delete_jellyseerr_user(username)
if jellyseerr_result:
jellyseerr_success.append(username)
except Exception as e:
jellyseerr_result = False
messages = []
if emby_success:
messages.append(f"Following Emby users deleted successfully:\n{' '.join(emby_success)}")
if jellyfin_success:
messages.append(f"Following Jellyfin users deleted successfully:\n{' '.join(jellyfin_success)}")
if jellyseerr_success:
messages.append(f"Following Jellyseerr users deleted successfully:\n{' '.join(jellyseerr_success)}")
await update.message.reply_text("\n".join(messages))
# Function to create Emby user with copied settings from 'settings' user
async def create_emby_user(username, password):
# Get the 'settings' user's ID
settings_user_id = None
settings_url = f"{EMBY_URL}/emby/Users"
headers = {'X-Emby-Token': EMBY_API_KEY}
response = requests.get(settings_url, headers=headers)
if response.status_code != 200:
return False
users = response.json()
for user in users:
if user['Name'].lower() == SETTINGS_USER.lower():
settings_user_id = user['Id']
break
if not settings_user_id:
return False
# Create a new user with settings copied from the 'settings' user
user_data = {
'Name': username,
'Password': password,
'PasswordResetRequired': False, # Indicate that the user does not need to reset the password
'CopyFromUserId': settings_user_id,
'UserCopyOptions': ["UserPolicy", "UserConfiguration"]
}
create_user_url = f"{EMBY_URL}/emby/Users/New"
response = requests.post(create_user_url, headers=headers, json=user_data)
if response.status_code != 200:
return False
# Setting the password separately if needed
password_url = f"{EMBY_URL}/emby/Users/{response.json()['Id']}/Password"
password_data = {
"CurrentPw": "", # No current password, since it's a new user
"NewPw": password
}
password_response = requests.post(password_url, headers=headers, json=password_data)
return password_response.status_code == 204
# Function to create Jellyfin user
async def create_jellyfin_user(username, password):
url = f"{JELLYFIN_URL}/Users/New"
headers = {'X-MediaBrowser-Token': JELLYFIN_API_KEY, 'Content-Type': 'application/json'}
data = {'Name': username, 'Password': password}
response = requests.post(url, headers=headers, json=data)
return response.status_code == 200
# Function to delete Emby user
async def delete_emby_user(username):
# Get the user's ID first
url = f"{EMBY_URL}/emby/Users"
headers = {'X-Emby-Token': EMBY_API_KEY}
response = requests.get(url, headers=headers)
if response.status_code != 200:
return False
users = response.json()
user_id = None
for user in users:
if user['Name'].lower() == username.lower():
user_id = user['Id']
break
if not user_id:
return False
# Delete the user
url = f"{EMBY_URL}/emby/Users/{user_id}"
response = requests.delete(url, headers=headers)
return response.status_code == 204
# Function to delete Jellyfin user
async def delete_jellyfin_user(username):
# Get the user's ID first
url = f"{JELLYFIN_URL}/Users"
headers = {'X-MediaBrowser-Token': JELLYFIN_API_KEY}
response = requests.get(url, headers=headers)
if response.status_code != 200:
return False
users = response.json()
user_id = None
for user in users:
if user['Name'].lower() == username.lower():
user_id = user['Id']
break
if not user_id:
return False
# Delete the user
url = f"{JELLYFIN_URL}/Users/{user_id}"
response = requests.delete(url, headers=headers)
return response.status_code == 204
# Function to delete Jellyseerr user
async def delete_jellyseerr_user(username):
# Get the user's ID first
url = f"{JELLYSEERR_URL}/api/v1/user"
headers = {'X-Api-Key': JELLYSEERR_API_KEY}
response = requests.get(url, headers=headers)
if response.status_code != 200:
return False
data = response.json()
users = data.get('results', [])
# Check if the response contains the expected user data
if isinstance(users, list): # Assuming users is a list of dictionaries
user_id = None
for user in users:
if isinstance(user, dict) and user.get('jellyfinUsername', '').lower() == username.lower():
user_id = user['id']
break
if not user_id:
return False
# Delete the user
url = f"{JELLYSEERR_URL}/api/v1/user/{user_id}"
response = requests.delete(url, headers=headers)
# Check for success status codes (204 or 200)
if response.status_code in [200, 204]:
return True
else:
print(f"Unexpected status code when deleting Jellyseerr user: {response.status_code}")
return False
else:
print("Unexpected response format:", users)
return False
# Function to import Jellyfin users into Jellyseerr
async def import_jellyfin_users_to_jellyseerr(new_username):
# First, get the list of Jellyfin users
url = f"{JELLYSEERR_URL}/api/v1/settings/jellyfin/users"
headers = {'X-Api-Key': JELLYSEERR_API_KEY}
response = requests.get(url, headers=headers)
if response.status_code != 200:
return False
users = response.json()
new_user = None
# Find the newly created user by username
for user in users:
if user['username'].lower() == new_username.lower():
new_user = user
break
if not new_user:
return False
# Import the new user into Jellyseerr
import_url = f"{JELLYSEERR_URL}/api/v1/user/import-from-jellyfin"
import_data = {'jellyfinUserIds': [new_user['id']]}
import_response = requests.post(import_url, headers=headers, json=import_data)
return import_response.status_code == 201
# Main function
def main():
application = Application.builder().token(TELEGRAM_API_TOKEN).build()
application.add_handler(CommandHandler('adduser', add_user))
application.add_handler(CommandHandler('deluser', del_user))
# Start the bot
application.run_polling()
if __name__ == '__main__':
main()