-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
474 lines (407 loc) · 14.7 KB
/
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
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import asyncio
import logging
import math
import os
import time
from typing import List
from urllib import request
import pymongo
import requests
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from pyquery import PyQuery as pq
from telethon import TelegramClient, events
from telethon.sync import TelegramClient
from telethon.tl.custom import Button
from telethon.tl.functions.users import GetFullUserRequest
from telethon.tl.types import DocumentAttributeVideo
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
level=logging.WARNING)
logger = logging.getLogger(__name__)
APP_ID = os.environ.get("APP_ID", None)
APP_HASH = os.environ.get("APP_HASH", None)
BOT_TOKEN = os.environ.get("BOT_TOKEN", None)
TMP_DOWNLOAD_DIRECTORY = os.environ.get(
"TMP_DOWNLOAD_DIRECTORY", "./DOWNLOADS/")
MONGO_DB = os.environ.get("MONGO_DB", None)
bot = TelegramClient('pinterestbot', APP_ID, APP_HASH).start(
bot_token=BOT_TOKEN)
msg = """
`Halo, Saya Adalah bot pinterest, saya bisa mendownload video atau gambar via Pinterest.`
Şunları yapabilirim:
`Saya Bisa:`
👉 **Untuk Men Download a video:** `/pvid pinterestURL`
👉 **Untuk Men Download Gambar:** `/pimg pinterestURL`
"""
SESSION_ADI = "pinterest"
class pinterest_db:
def __init__(self):
client = pymongo.MongoClient(MONGO_DB)
db = client['Telegram']
self.collection = db[SESSION_ADI]
def ara(self, sorgu: dict):
say = self.collection.count_documents(sorgu)
if say == 1:
return self.collection.find_one(sorgu, {'_id': 0})
elif say > 1:
cursor = self.collection.find(sorgu, {'_id': 0})
return {
bak['uye_id']: {
"uye_nick": bak['uye_nick'],
"uye_adi": bak['uye_adi']
}
for bak in cursor
}
else:
return None
def ekle(self, uye_id, uye_nick, uye_adi):
if not self.ara({'uye_id': {'$in': [str(uye_id), int(uye_id)]}}):
return self.collection.insert_one({
"uye_id": uye_id,
"uye_nick": uye_nick,
"uye_adi": uye_adi,
})
else:
return None
def sil(self, uye_id):
if not self.ara({'uye_id': {'$in': [str(uye_id), int(uye_id)]}}):
return None
self.collection.delete_one(
{'uye_id': {'$in': [str(uye_id), int(uye_id)]}})
return True
@property
def kullanici_idleri(self):
return list(self.ara({'uye_id': {'$exists': True}}).keys())
async def log_yolla(event):
j = await event.client(
GetFullUserRequest(
event.chat_id
)
)
uye_id = j.user.id
uye_nick = f"@{j.user.username}" if j.user.username else None
uye_adi = f"{j.user.first_name or ''} {j.user.last_name or ''}".strip()
komut = event.text
# Kullanıcı Kaydet
db = pinterest_db()
db.ekle(uye_id, uye_nick, uye_adi)
# total number of users using the bot
@bot.on(events.NewMessage(pattern="/kul_say"))
async def say(event):
j = await event.client(
GetFullUserRequest(
event.chat_id
)
)
db = pinterest_db()
db.ekle(j.user.id, j.user.username, j.user.first_name)
def KULLANICILAR(): return db.kullanici_idleri
await event.client.send_message("By_Rio", f"ℹ️ `{len(KULLANICILAR())}` __Adet Kullanıcıya Sahipsin..__")
# Command to make an announcement to users using the bot
@bot.on(events.NewMessage(pattern="/duyuru ?(.*)"))
async def duyuru(event):
# < Başlangıç
await log_yolla(event)
ilk_mesaj = await event.client.send_message(event.chat_id, "⌛️ `Hallediyorum..`",
reply_to=event.chat_id,
link_preview=False
)
# ------------------------------------------------------------- Başlangıç >
db = pinterest_db()
def KULLANICILAR(): return db.kullanici_idleri
if not KULLANICILAR():
await ilk_mesaj.edit("ℹ️ __Start Time..__")
return
if not event.message.reply_to:
await ilk_mesaj.edit("⚠️ __Note..__")
return
basarili = 0
hatalar = []
mesaj_giden_kisiler = []
get_reply_msg = await event.get_reply_message()
for kullanici_id in KULLANICILAR():
try:
await event.client.send_message(
entity=kullanici_id,
message=get_reply_msg.message
)
mesaj_giden_kisiler.append(kullanici_id)
basarili += 1
except Exception as hata:
hatalar.append(type(hata).__name__)
db.sil(kullanici_id)
mesaj = f"⁉️ `{len(hatalar)}` __Adet Kişiye Mesaj Atamadım ve DB'den Sildim..__\n\n" if hatalar else ""
mesaj += f"📜 `{basarili}` __Adet Kullanıcıya Mesaj Attım..__"
await ilk_mesaj.edit(mesaj)
@bot.on(events.NewMessage(pattern="/start", func=lambda e: e.is_private))
async def start(event):
await log_yolla(event)
j = await event.client(
GetFullUserRequest(
event.chat_id
)
)
mesaj = f"Gönderen [{j.user.first_name}](tg://user?id={event.chat_id})\nMesaj: {event.message.message}"
await bot.send_message(
"By_Azade",
mesaj
)
if event:
markup = bot.build_reply_markup(
[
[
Button.url(
text='📍 Channel', url="t.me/rioprojects"),
Button.url(
text='👤 Developer', url="t.me/fckualot")
],
[
Button.url(text="🔗 Group Support",
url="https://t.me/riogroupsupport")
]
]
)
await bot.send_message(event.chat_id, msg, buttons=markup, link_preview=False)
@bot.on(events.NewMessage(pattern="/pvid ?(.*)", func=lambda e: e.is_private))
async def vid(event):
await log_yolla(event)
try:
j = await event.client(
GetFullUserRequest(
event.chat_id
)
)
mesaj = f"Gönderen [{j.user.first_name}](tg://user?id={event.chat_id})\nMesaj: {event.message.message}"
await bot.send_message(
"By_Azade",
mesaj
)
markup = bot.build_reply_markup([Button.url(
text='📍 Channel', url="t.me/rioprojects"),
Button.url(
text='👤 Developer', url="t.me/fckualot")
])
url = event.pattern_match.group(1)
if url:
x = await event.reply("`işlem yapılıyor bekleyiniz...`")
get_url = get_download_url(url)
j = download_video(get_url)
thumb_image_path = TMP_DOWNLOAD_DIRECTORY + "thumb_image.jpg"
if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY):
os.makedirs(TMP_DOWNLOAD_DIRECTORY)
metadata = extractMetadata(createParser(j))
duration = 0
if metadata.has("duration"):
duration = metadata.get('duration').seconds
width = 0
height = 0
thumb = None
if os.path.exists(thumb_image_path):
thumb = thumb_image_path
else:
thumb = await take_screen_shot(
j,
os.path.dirname(os.path.abspath(j)),
(duration / 2)
)
c_time = time.time()
await event.client.send_file(
event.chat_id,
j,
thumb=thumb,
caption="**@Pinterestdown_Robot** tarafından indirilmiştir\n\nDownloaded by **@Pinterestdown_Robot**",
force_document=False,
allow_cache=False,
reply_to=event.message.id,
buttons=markup,
attributes=[
DocumentAttributeVideo(
duration=duration,
w=width,
h=height,
round_message=False,
supports_streaming=True
)
],
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, event, c_time, "yükleniyor...")
)
)
await event.delete()
await x.delete()
os.remove(TMP_DOWNLOAD_DIRECTORY + 'pinterest_video.mp4')
os.remove(thumb_image_path)
else:
await event.reply("**bana komutla beraber link gönder.**\n\n`send me the link with the command.`")
except FileNotFoundError:
return
@bot.on(events.NewMessage(pattern="/pimg ?(.*)", func=lambda e: e.is_private))
async def img(event):
await log_yolla(event)
j = await event.client(
GetFullUserRequest(
event.chat_id
)
)
mesaj = f"Gönderen [{j.user.first_name}](tg://user?id={event.chat_id})\nMesaj: {event.message.message}"
await bot.send_message(
"By_Azade",
mesaj
)
markup = bot.build_reply_markup([Button.url(
text='📍 Channel', url="t.me/rioprojects"),
Button.url(
text='👤 Rio', url="t.me/fckualot")
])
url = event.pattern_match.group(1)
if url:
x = await event.reply("`İşlem yapılıyor lütfen bekleyiniz...`\n\nProcessing please wait ...")
get_url = get_download_url(url)
j = download_image(get_url)
if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY):
os.makedirs(TMP_DOWNLOAD_DIRECTORY)
c_time = time.time()
await event.client.send_file(
event.chat_id,
j,
caption="**@pinterestriobot** tarafından indirilmiştir\n\nDownloaded by **@pinterestriobot**",
force_document=False,
allow_cache=False,
reply_to=event.message.id,
buttons=markup,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, event, c_time, "yükleniyor...")
)
)
await event.delete()
await x.delete()
os.remove(TMP_DOWNLOAD_DIRECTORY + 'pinterest_iamge.jpg')
else:
await event.reply("**bana komutla beraber link gönder.**\n\n`send me the link with the command.`")
async def run_command(command: List[str]) -> (str, str):
process = await asyncio.create_subprocess_exec(
*command,
# stdout must a pipe to be accessible as process.stdout
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
# Wait for the subprocess to finish
stdout, stderr = await process.communicate()
e_response = stderr.decode().strip()
t_response = stdout.decode().strip()
return t_response, e_response
async def take_screen_shot(video_file, output_directory, ttl):
# https://stackoverflow.com/a/13891070/4723940
out_put_file_name = output_directory + \
"/" + str(time.time()) + ".jpg"
file_genertor_command = [
"ffmpeg",
"-ss",
str(ttl),
"-i",
video_file,
"-vframes",
"1",
out_put_file_name
]
# width = "90"
t_response, e_response = await run_command(file_genertor_command)
if os.path.lexists(out_put_file_name):
return out_put_file_name
logger.info(e_response)
logger.info(t_response)
return None
def humanbytes(size):
"""Input size in bytes,
outputs in a human readable format"""
# https://stackoverflow.com/a/49361727/4723940
if not size:
return ""
# 2 ** 10 = 1024
power = 2 ** 10
raised_to_pow = 0
dict_power_n = {
0: "",
1: "Ki",
2: "Mi",
3: "Gi",
4: "Ti"
}
while size > power:
size /= power
raised_to_pow += 1
return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B"
def time_formatter(seconds: int) -> str:
"""Inputs time in seconds, to get beautified time,
as string"""
result = ""
v_m = 0
remainder = seconds
r_ange_s = {
"days": (24 * 60 * 60),
"hours": (60 * 60),
"minutes": 60,
"seconds": 1
}
for age, divisor in r_ange_s.items():
v_m, remainder = divmod(remainder, divisor)
v_m = int(v_m)
if v_m != 0:
result += f" {v_m} {age} "
return result
async def progress(current, total, event, start, type_of_ps):
"""Generic progress_callback for both
upload.py and download.py"""
now = time.time()
diff = now - start
if round(diff % 10.00) == 0 or current == total:
percentage = current * 100 / total
elapsed_time = round(diff)
if elapsed_time == 0:
return
speed = current / diff
time_to_completion = round((total - current) / speed)
estimated_total_time = elapsed_time + time_to_completion
progress_str = "[{0}{1}]\nPercent: {2}%\n".format(
''.join(["█" for _ in range(math.floor(percentage / 5))]),
''.join(["░" for _ in range(20 - math.floor(percentage / 5))]),
round(percentage, 2))
tmp = progress_str + \
"{0} of {1}\nETA: {2}".format(
humanbytes(current),
humanbytes(total),
time_formatter(estimated_total_time)
)
await event.edit("{}\n {}".format(
type_of_ps,
tmp
))
# Function to get download url
def get_download_url(link):
# Make request to website
post_request = requests.post(
'https://www.expertsphp.com/download.php', data={'url': link})
# Get content from post request
request_content = post_request.content
str_request_content = str(request_content, 'utf-8')
return pq(str_request_content)('table.table-condensed')('tbody')('td')(
'a'
).attr('href')
# Function to download video
def download_video(url):
if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY):
os.makedirs(TMP_DOWNLOAD_DIRECTORY)
video_to_download = request.urlopen(url).read()
with open(TMP_DOWNLOAD_DIRECTORY + 'pinterest_video.mp4', 'wb') as video_stream:
video_stream.write(video_to_download)
return TMP_DOWNLOAD_DIRECTORY + 'pinterest_video.mp4'
# Function to download image
def download_image(url):
if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY):
os.makedirs(TMP_DOWNLOAD_DIRECTORY)
image_to_download = request.urlopen(url).read()
with open(TMP_DOWNLOAD_DIRECTORY + 'pinterest_iamge.jpg', 'wb') as photo_stream:
photo_stream.write(image_to_download)
return TMP_DOWNLOAD_DIRECTORY + 'pinterest_iamge.jpg'
bot.start()
bot.run_until_disconnected()