forked from MrTamilKiD/AutoFilterBot-Beta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
277 lines (246 loc) · 8.94 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
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
from typing import Union
import re
import os
import pytz
import time
from datetime import datetime
from typing import List, Any, Union, Optional, AsyncGenerator
from database.users_chats_db import db
from bs4 import BeautifulSoup
import requests
from shortzy import Shortzy
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
imdb = Cinemagoer()
# temp db for banned
class temp(object):
START_TIME = 0
BANNED_USERS = []
BANNED_CHATS = []
ME = None
CURRENT=0
CANCEL = False
U_NAME = None
B_NAME = None
SETTINGS = {}
FILES = {}
USERS_CANCEL = False
GROUPS_CANCEL = False
BOT = None
async def is_subscribed(bot, query, channel=AUTH_CHANNEL):
btn = []
for id in channel:
chat = await bot.get_chat(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:
logger.exception(e)
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 iter_messages(client, chat_id: Union[int, str], limit: int, offset: int = 0) -> Optional[AsyncGenerator["types.Message", None]]:
"""Iterate through a chat sequentially.
This convenience method does the same as repeatedly calling :meth:`~pyrogram.Client.get_messages` in a loop, thus saving
you from the hassle of setting up boilerplate code. It is useful for getting the whole chat messages with a
single call.
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact that exists in your Telegram address book you can use his phone number (str).
limit (``int``):
Identifier of the last message to be returned.
offset (``int``, *optional*):
Identifier of the first message to be returned.
Defaults to 0.
Returns:
``Generator``: A generator yielding :obj:`~pyrogram.types.Message` objects.
Example:
.. code-block:: python
for message in app.iter_messages("pyrogram", 1, 15000):
print(message.text)
"""
current = offset
while True:
new_diff = min(200, limit - current)
if new_diff <= 0:
return
messages = await client.get_messages(chat_id, list(range(current, current+new_diff+1)))
for message in messages:
yield message
current += 1
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 = await db.get_verify_status(user_id)
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
await db.update_verify_status(user_id, current)
async def broadcast_messages(user_id, message):
try:
await message.copy(chat_id=user_id)
return "Success"
except FloodWait as e:
await asyncio.sleep(e.value)
return await broadcast_messages(user_id, message)
except Exception as e:
await db.delete_user(int(user_id))
return "Error"
async def groups_broadcast_messages(chat_id, message):
try:
k = await message.copy(chat_id=chat_id)
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)
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