Completed
Push — master ( d94fc7...f6b49c )
by Anas
8s
created

extract_url()   A

Complexity

Conditions 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
# Module courtesy of Slko
4
import requests
5
import subprocess
6
import os.path
7
8
9
def extract_url(entity, text):
10
    if entity["type"] == "text_link":
11
        return entity["url"]
12
    elif entity["type"] == "url":
13
        offset = entity["offset"]
14
        length = entity["length"]
15
        return text[offset:offset+length]
16
    else:
17
        return None
18
19
20
def is_image(path):
21
    image_extensions = (".jpg", ".png", ".gif")
22
    if path is None:
23
        return False
24
    return path.casefold().endswith(image_extensions)
25
26
27
def get_image(bot, update, dl_path):
28
    output = os.path.join(dl_path, "original.jpg")
29
    temp_png = os.path.join(dl_path, "original.png")
30
    reply = update.message.reply_to_message
31
    if reply is None:
32
        return False
33
    # Entities; url, text_link
34
    if reply.entities is not None:
35
        urls = (extract_url(x, reply.text) for x in reply.entities)
36
        images = [x for x in urls if is_image(x)]
37
        if len(images) > 0:
38
            r = requests.get(images[0])  # use only first image url
39
            with open(output, "wb") as f:
40
                f.write(r.content)
41
            return True
42
    # Document
43
    if reply.document is not None and is_image(reply.document.file_name):
44
        bot.getFile(reply.document.file_id).download(output)
45
        return True
46
    # Sticker
47
    if reply.sticker is not None:
48
        bot.getFile(reply.sticker.file_id).download(output)
49
        stick = "convert  " + temp_png + " -background white -flatten " + output
50
        subprocess.run(stick, shell=True)
51
        return True
52
    # Photo in reply
53
    if reply.photo is not None:
54
        bot.getFile(reply.photo[-1].file_id).download(output)
55
        return True
56
    return False
57