Passed
Push — master ( 1eef4e...280449 )
by Anas
02:26
created

modules.gelbooru_search.get_image()   A

Complexity

Conditions 3

Size

Total Lines 17
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
nop 1
dl 0
loc 17
rs 9.6
c 0
b 0
f 0
1
#by Linaname
2
from modules.logging import logging_decorator
3
from telegram.ext import CommandHandler
4
from telegram import ChatAction
5
import requests
6
import random
7
8
9
def module_init(gd):
10
    commands = gd.config["commands"]
11
    for command in commands:
12
        gd.dp.add_handler(CommandHandler(command, gelbooru_search, pass_args=True))
13
14
15 View Code Duplication
@logging_decorator("gelbooru")
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
16
def gelbooru_search(bot, update, args):
17
    update.message.chat.send_action(ChatAction.UPLOAD_PHOTO)
18
    query = " ".join(args)
19
    try:
20
        direct_link, page_link = get_image(query)
21
    except:
22
        update.message.reply_text("Sorry, something went wrong!")
23
        return
24
    if direct_link is None:
25
        update.message.reply_text("Nothing found!")
26
        return
27
    msg_text = "[Image]({})".format(direct_link) + "\n" + "[View post]({})".format(page_link)
28
    update.message.reply_text(msg_text, parse_mode="Markdown")
29
    return(query)
30
31
32
def get_image(query):
33
    params = {
34
        "page": "dapi",
35
        "s": "post",
36
        "q": "index",
37
        "json": "1",
38
        "tags": query,
39
    }
40
    response = requests.get("https://gelbooru.com/index.php", params=params)
41
    if not response.text:
42
        return None, None
43
    result_list = response.json()
44
    if not result_list:
45
        return None, None
46
    post = random.choice(result_list)
47
    direct_link, page_link = post.get("file_url"), "https://gelbooru.com/index.php?page=post&s=view&id="+str(post.get("id"))
48
    return direct_link, page_link
49