-
Notifications
You must be signed in to change notification settings - Fork 112
/
utils.py
275 lines (246 loc) · 8.39 KB
/
utils.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
import logging
from pyrogram.errors import InputUserDeactivated, UserNotParticipant, FloodWait, UserIsBlocked, PeerIdInvalid
from info import AUTH_CHANNEL, LONG_IMDB_DESCRIPTION
from imdb import Cinemagoer
import asyncio
from pyrogram.types import Message, InlineKeyboardButton, ChatJoinRequest
from pyrogram import enums
import os
import pytz
import time, re
from datetime import datetime
from typing import List, Any, Union, Optional, AsyncGenerator
from database.users_chats_db import db
from shortzy import Shortzy
imdb = Cinemagoer()
# temp db
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
async def is_subscribed(bot, query, channel):
btn = []
for id in channel:
chat = await bot.get_chat(int(id))
try:
await bot.get_chat_member(id, query.from_user.id)
except UserNotParticipant:
btn.append(
[InlineKeyboardButton(f'Join {chat.title}', url=chat.invite_link)]
)
except Exception as e:
pass
return btn
async def get_poster(query, bulk=False, id=False, file=None):
if not id:
query = (query.strip()).lower()
title = query
year = re.findall(r'[1-2]\d{3}$', query, re.IGNORECASE)
if year:
year = list_to_str(year[:1])
title = (query.replace(year, "")).strip()
elif file is not None:
year = re.findall(r'[1-2]\d{3}', file, re.IGNORECASE)
if year:
year = list_to_str(year[:1])
else:
year = None
movieid = imdb.search_movie(title.lower(), results=10)
if not movieid:
return None
if year:
filtered=list(filter(lambda k: str(k.get('year')) == str(year), movieid))
if not filtered:
filtered = movieid
else:
filtered = movieid
movieid=list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered))
if not movieid:
movieid = filtered
if bulk:
return movieid
movieid = movieid[0].movieID
else:
movieid = query
movie = imdb.get_movie(movieid)
if movie.get("original air date"):
date = movie["original air date"]
elif movie.get("year"):
date = movie.get("year")
else:
date = "N/A"
plot = ""
if not LONG_IMDB_DESCRIPTION:
plot = movie.get('plot')
if plot and len(plot) > 0:
plot = plot[0]
else:
plot = movie.get('plot outline')
if plot and len(plot) > 800:
plot = plot[0:800] + "..."
return {
'title': movie.get('title'),
'votes': movie.get('votes'),
"aka": list_to_str(movie.get("akas")),
"seasons": movie.get("number of seasons"),
"box_office": movie.get('box office'),
'localized_title': movie.get('localized title'),
'kind': movie.get("kind"),
"imdb_id": f"tt{movie.get('imdbID')}",
"cast": list_to_str(movie.get("cast")),
"runtime": list_to_str(movie.get("runtimes")),
"countries": list_to_str(movie.get("countries")),
"certificates": list_to_str(movie.get("certificates")),
"languages": list_to_str(movie.get("languages")),
"director": list_to_str(movie.get("director")),
"writer":list_to_str(movie.get("writer")),
"producer":list_to_str(movie.get("producer")),
"composer":list_to_str(movie.get("composer")) ,
"cinematographer":list_to_str(movie.get("cinematographer")),
"music_team": list_to_str(movie.get("music department")),
"distributors": list_to_str(movie.get("distributors")),
'release_date': date,
'year': movie.get('year'),
'genres': list_to_str(movie.get("genres")),
'poster': movie.get('full-size cover url'),
'plot': plot,
'rating': str(movie.get("rating")),
'url':f'https://www.imdb.com/title/tt{movieid}'
}
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, verified_time=0, link=""):
current = await get_verify_status(user_id)
current['verify_token'] = verify_token
current['is_verified'] = is_verified
current['verified_time'] = verified_time
current['link'] = link
temp.VERIFICATIONS[user_id] = current
await db.update_verify_status(user_id, current)
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):
"""Get size in readable format"""
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])
def list_to_str(k):
if not k:
return "N/A"
elif len(k) == 1:
return str(k[0])
else:
return ', '.join(f'{elem}' for elem in k)
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():
tz = pytz.timezone('Asia/Colombo')
time = datetime.now(tz)
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
async def delayed_delete(Bot, message, delay):
await asyncio.sleep(delay)
await Bot.delete_messages(chat_id=message.chat.id, message_ids=message.id)