-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathutils.py
More file actions
372 lines (319 loc) · 10.9 KB
/
utils.py
File metadata and controls
372 lines (319 loc) · 10.9 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
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
from pyrogram.errors import UserNotParticipant, FloodWait
from info import LONG_IMDB_DESCRIPTION, ADMINS, IS_PREMIUM, TIME_ZONE, TMDB_API_KEY
import asyncio
from pyrogram.types import InlineKeyboardButton
from pyrogram import enums
import re
from datetime import datetime
from database.users_chats_db import db
from shortzy import Shortzy
import requests, pytz
class temp(object):
START_TIME = 0
BANNED_USERS = []
BANNED_CHATS = []
ME = None
CANCEL = False
U_NAME = None
B_NAME = None
SETTINGS = {}
VERIFICATIONS = {}
FILES = {}
USERS_CANCEL = False
GROUPS_CANCEL = False
BOT = None
PREMIUM = {}
async def is_subscribed(bot, query):
btn = []
if await is_premium(query.from_user.id, bot):
return btn
stg = db.get_bot_sttgs()
if not stg or not stg.get('FORCE_SUB_CHANNELS'):
return btn
for id in stg.get('FORCE_SUB_CHANNELS').split(' '):
chat = await bot.get_chat(int(id))
try:
await bot.get_chat_member(int(id), query.from_user.id)
except UserNotParticipant:
btn.append(
[InlineKeyboardButton(f'Join : {chat.title}', url=chat.invite_link)]
)
if stg and stg.get('REQUEST_FORCE_SUB_CHANNELS') and not db.find_join_req(query.from_user.id):
id = stg.get('REQUEST_FORCE_SUB_CHANNELS')
chat = await bot.get_chat(int(id))
try:
await bot.get_chat_member(int(id), query.from_user.id)
except UserNotParticipant:
url = await bot.create_chat_invite_link(int(id), creates_join_request=True)
btn.append(
[InlineKeyboardButton(f'Request : {chat.title}', url=url.invite_link)]
)
return btn
def upload_image(file_path):
with open(file_path, 'rb') as f:
files = {'files[]': f}
response = requests.post("https://uguu.se/upload", files=files)
if response.status_code == 200:
try:
data = response.json()
return data['files'][0]['url'].replace('\\/', '/')
except Exception as e:
return None
else:
return None
def list_to_str(k):
if not k:
return "N/A"
elif len(k) == 1:
return str(k[0])
else:
return ", ".join(str(i) for i in k)
async def get_poster(query, bulk=False, id=False, file=None):
TMDB_BASE = "https://api.themoviedb.org/3"
year = None
title = query
if not id:
query = query.strip()
year_match = re.findall(r"[1-2]\d{3}$", query)
if year_match:
year = year_match[0]
title = query.replace(year, "").strip()
elif file:
file_year = re.findall(r"[1-2]\d{3}", file)
if file_year:
year = file_year[0]
url = f"{TMDB_BASE}/search/multi"
params = {
"api_key": TMDB_API_KEY,
"query": title
}
res = requests.get(url, params=params).json()
results = [
r for r in res.get("results", [])
if r.get("media_type") in ["movie", "tv"]
]
if not results:
return None
if year:
filtered = []
for r in results:
release = r.get("release_date") or r.get("first_air_date")
if release and release.startswith(str(year)):
filtered.append(r)
if filtered:
results = filtered
if bulk:
_bulk = []
for r in results:
_title = r.get("title") or r.get("name")
if _title:
_bulk.append({
"title": _title,
"id": r["id"]
})
return _bulk
data = results[0]
tmdb_id = data["id"]
media_type = data["media_type"]
else:
tmdb_id = query
movie_test = requests.get(
f"{TMDB_BASE}/movie/{tmdb_id}",
params={"api_key": TMDB_API_KEY}
)
if movie_test.status_code == 200:
media_type = "movie"
data = movie_test.json()
else:
media_type = "tv"
data = requests.get(
f"{TMDB_BASE}/tv/{tmdb_id}",
params={"api_key": TMDB_API_KEY}
).json()
if not id:
data = requests.get(
f"{TMDB_BASE}/{media_type}/{tmdb_id}",
params={"api_key": TMDB_API_KEY}
).json()
title = data.get("title") or data.get("name")
poster = None
if data.get("poster_path"):
poster = f"https://image.tmdb.org/t/p/original{data['poster_path']}"
release_date = data.get("release_date") or data.get("first_air_date")
genres = list_to_str([g["name"] for g in data.get("genres", [])])
runtime = None
if media_type == "movie":
runtime = data.get("runtime")
else:
runtime = list_to_str(data.get("episode_run_time"))
plot = data.get("overview")
rating = data.get("vote_average")
votes = data.get("vote_count")
languages = list_to_str([l["english_name"] for l in data.get("spoken_languages", [])])
countries = list_to_str([c["name"] for c in data.get("production_countries", [])])
return {
"title": title,
"tmdb_id": tmdb_id,
"kind": media_type,
"languages": languages,
"countries": countries,
"release_date": release_date,
"year": release_date[:4] if release_date else None,
"genres": genres,
"runtime": runtime,
"rating": rating,
"votes": votes,
"poster": poster,
"plot": plot,
"url": f"https://www.themoviedb.org/{media_type}/{tmdb_id}"
}
async def is_check_admin(bot, chat_id, user_id):
try:
member = await bot.get_chat_member(chat_id, user_id)
return member.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]
except:
return False
async def get_verify_status(user_id):
verify = temp.VERIFICATIONS.get(user_id)
if not verify:
verify = await db.get_verify_status(user_id)
temp.VERIFICATIONS[user_id] = verify
return verify
async def update_verify_status(user_id, verify_token="", is_verified=False, link="", expire_time=0):
current = await get_verify_status(user_id)
current['verify_token'] = verify_token
current['is_verified'] = is_verified
current['link'] = link
current['expire_time'] = expire_time
temp.VERIFICATIONS[user_id] = current
await db.update_verify_status(user_id, current)
async def is_premium(user_id, bot):
if not IS_PREMIUM:
return True
if user_id in ADMINS:
return True
mp = db.get_plan(user_id)
if mp['premium']:
if mp['expire'] < datetime.now():
await bot.send_message(user_id, f"Your premium {mp['plan']} plan is expired in {mp['expire'].strftime('%Y.%m.%d %H:%M:%S')}, use /plan to activate new plan again")
mp['expire'] = ''
mp['plan'] = ''
mp['premium'] = False
db.update_plan(user_id, mp)
return False
return True
else:
return False
async def check_premium(bot):
while True:
pr = [i for i in db.get_premium_users() if i['status']['premium']]
for p in pr:
mp = p['status']
if mp['expire'] < datetime.now():
try:
await bot.send_message(
p['id'],
f"Your premium {mp['plan']} plan is expired in {mp['expire'].strftime('%Y.%m.%d %H:%M:%S')}, use /plan to activate new plan again"
)
except Exception:
pass
mp['expire'] = ''
mp['plan'] = ''
mp['premium'] = False
db.update_plan(p['id'], mp)
await asyncio.sleep(1200)
async def broadcast_messages(user_id, message, pin):
try:
m = await message.copy(chat_id=user_id)
if pin:
await m.pin(both_sides=True)
return "Success"
except FloodWait as e:
await asyncio.sleep(e.value)
return await broadcast_messages(user_id, message, pin)
except Exception as e:
await db.delete_user(int(user_id))
return "Error"
async def groups_broadcast_messages(chat_id, message, pin):
try:
k = await message.copy(chat_id=chat_id)
if pin:
try:
await k.pin()
except:
pass
return "Success"
except FloodWait as e:
await asyncio.sleep(e.value)
return await groups_broadcast_messages(chat_id, message, pin)
except Exception as e:
await db.delete_chat(chat_id)
return "Error"
async def get_settings(group_id):
settings = temp.SETTINGS.get(group_id)
if not settings:
settings = await db.get_settings(group_id)
temp.SETTINGS.update({group_id: settings})
return settings
async def save_group_settings(group_id, key, value):
current = await get_settings(group_id)
current.update({key: value})
temp.SETTINGS.update({group_id: current})
await db.update_settings(group_id, current)
def get_size(size):
units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
size = float(size)
i = 0
while size >= 1024.0 and i < len(units):
i += 1
size /= 1024.0
return "%.2f %s" % (size, units[i])
async def get_shortlink(url, api, link):
shortzy = Shortzy(api_key=api, base_site=url)
link = await shortzy.convert(link)
return link
def get_readable_time(seconds):
periods = [('d', 86400), ('h', 3600), ('m', 60), ('s', 1)]
result = ''
for period_name, period_seconds in periods:
if seconds >= period_seconds:
period_value, seconds = divmod(seconds, period_seconds)
result += f'{int(period_value)}{period_name}'
return result
def get_wish():
time = datetime.now(pytz.timezone(TIME_ZONE))
now = time.strftime("%H")
if now < "12":
status = "ɢᴏᴏᴅ ᴍᴏʀɴɪɴɢ 🌞"
elif now < "18":
status = "ɢᴏᴏᴅ ᴀꜰᴛᴇʀɴᴏᴏɴ 🌗"
else:
status = "ɢᴏᴏᴅ ᴇᴠᴇɴɪɴɢ 🌘"
return status
async def get_seconds(time_string):
def extract_value_and_unit(ts):
value = ""
unit = ""
index = 0
while index < len(ts) and ts[index].isdigit():
value += ts[index]
index += 1
unit = ts[index:]
if value:
value = int(value)
return value, unit
value, unit = extract_value_and_unit(time_string)
if unit == 's':
return value
elif unit == 'min':
return value * 60
elif unit == 'hour':
return value * 3600
elif unit == 'day':
return value * 86400
elif unit == 'month':
return value * 86400 * 30
elif unit == 'year':
return value * 86400 * 365
else:
return 0