-
Notifications
You must be signed in to change notification settings - Fork 199
/
utils.py
308 lines (287 loc) · 9.41 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
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
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
import shortzy
from pyrogram.types import Message, InlineKeyboardButton
from pyrogram import enums
import pytz
import time
import re
import os
from shortzy import Shortzy
from datetime import datetime, timedelta, timezone
from typing import Any
from database.users_chats_db import db
import requests
import aiohttp
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
BANNED = {}
imdb = Cinemagoer()
class temp(object):
ME = None
CURRENT=int(os.environ.get("SKIP", 2))
CANCEL = False
U_NAME = None
B_NAME = None
B_LINK = None
SETTINGS = {}
FILES_ID = {}
USERS_CANCEL = False
GROUPS_CANCEL = False
CHAT = {}
async def is_subscribed(bot, user_id, channel_id):
try:
user = await bot.get_chat_member(channel_id, user_id)
except UserNotParticipant:
pass
except Exception as e:
pass
else:
if user.status != enums.ChatMemberStatus.BANNED:
return True
return False
async def is_req_subscribed(bot, query):
if await db.find_join_req(query.from_user.id):
return True
try:
user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
except UserNotParticipant:
pass
except Exception as e:
logger.exception(e)
else:
if user.status != enums.ChatMemberStatus.BANNED:
return True
return False
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 users_broadcast(user_id, message, is_pin):
try:
m=await message.copy(chat_id=user_id)
if is_pin:
await m.pin(both_sides=True)
return True, "Success"
except FloodWait as e:
await asyncio.sleep(e.x)
return await users_broadcast(user_id, message)
except InputUserDeactivated:
await db.delete_user(int(user_id))
logging.info(f"{user_id}-Removed from Database, since deleted account.")
return False, "Deleted"
except UserIsBlocked:
logging.info(f"{user_id} -Blocked the bot.")
await db.delete_user(user_id)
return False, "Blocked"
except PeerIdInvalid:
await db.delete_user(int(user_id))
logging.info(f"{user_id} - PeerIdInvalid")
return False, "Error"
except Exception as e:
return False, "Error"
async def groups_broadcast(chat_id, message, is_pin):
try:
m = await message.copy(chat_id=chat_id)
if is_pin:
try:
await m.pin()
except:
pass
return "Success"
except FloodWait as e:
await asyncio.sleep(e.x)
return await groups_broadcast(chat_id, message)
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])
def get_name(name):
regex = re.sub(r'@\w+', '', name)
return regex
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(link, grp_id, is_second_shortener=False, is_third_shortener=False):
settings = await get_settings(grp_id)
if is_third_shortener:
api, site = settings['api_three'], settings['shortner_three']
else:
if is_second_shortener:
api, site = settings['api_two'], settings['shortner_two']
else:
api, site = settings['api'], settings['shortner']
shortzy = Shortzy(api, site)
try:
link = await shortzy.convert(link)
except Exception as e:
link = await shortzy.get_quick_link(link)
return link
def get_file_id(message: "Message") -> Any:
media_types = (
"audio",
"document",
"photo",
"sticker",
"animation",
"video",
"voice",
"video_note",
)
if message.media:
for attr in media_types:
media = getattr(message, attr, None)
if media:
setattr(media, "message_type", attr)
return media
def get_hash(media_msg: Message) -> str:
media = get_file_id(media_msg)
return getattr(media, "file_unique_id", "")[:6]
def get_status():
tz = pytz.timezone('Asia/Colombo')
hour = datetime.now(tz).time().hour
if 5 <= hour < 12:
sts = "ɢᴏᴏᴅ ᴍᴏʀɴɪɴɢ"
elif 12 <= hour < 18:
sts = "ɢᴏᴏᴅ ᴀꜰᴛᴇʀɴᴏᴏɴ"
else:
sts = "ɢᴏᴏᴅ ᴇᴠᴇɴɪɴɢ"
return sts
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_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:].lstrip()
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
def get_readable_time(seconds):
periods = [('days', 86400), ('hour', 3600), ('min', 60), ('sec', 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