Passed
Push — master ( 280449...3506d6 )
by Anas
01:56
created

modules.anime_search.yandere_search()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
from modules.logging import logging_decorator
4
from telegram.ext import CommandHandler
5
from telegram import ChatAction
6
import requests
7
import random
8
9
10
def module_init(gd):      
11
    commands_gelbooru = gd.config["commands_gelbooru"]
12
    commands_yandere = gd.config["commands_yandere"]
13
    for command in commands_gelbooru:
14
        gd.dp.add_handler(CommandHandler(command, gelbooru_search, pass_args=True))
15
    for command in commands_yandere:
16
        gd.dp.add_handler(CommandHandler(command, yandere_search, pass_args=True))
17
18
19
@logging_decorator("yandere")
20
def yandere_search(bot, update, args):
21
    request_link = "https://yande.re/post.json?"
22
    image_link = "https://yande.re/post/show/"
23
    search(bot, update, args, request_link, image_link)
24
25
26
@logging_decorator("gelbooru")
27
def gelbooru_search(bot, update, args):
28
    request_link = "https://gelbooru.com/index.php?page=dapi&s=post&q=index&json=1"
29
    image_link = "https://gelbooru.com/index.php?page=post&s=view&id="
30
    search(bot, update, args, request_link, image_link)
31
32
33
def search(bot, update, args, request_link, image_link):
34
    update.message.chat.send_action(ChatAction.UPLOAD_PHOTO)
35
    query = " ".join(args)
36
    try:
37
        direct_link, page_link = get_image(query, request_link, image_link)
38
    except:
39
        update.message.reply_text("Sorry, something went wrong!")
40
        return
41
    if direct_link is None:
42
        update.message.reply_text("Nothing found!")
43
        return
44
    msg_text = "[Image]({})".format(direct_link) + "\n" + "[View post]({})".format(page_link)
45
    update.message.reply_text(msg_text, parse_mode="Markdown")
46
47
48
def get_image(query, request_link, image_link):
49
    params = {"tags": query}
50
    response = requests.get(request_link, params=params)
51
    result_list = response.json()
52
    if not response.text:
53
        return None, None
54
    if not result_list:
55
        return None, None
56
    post = random.choice(result_list)
57
    direct_link, page_link = post.get("file_url"), image_link+str(post.get("id"))
58
    return direct_link, page_link
59