Completed
Push — master ( 9ef7e8...322940 )
by Anas
55s
created

yandere_search()   B

Complexity

Conditions 5

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
c 1
b 0
f 0
dl 0
loc 20
rs 8.5454
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
from __future__ import unicode_literals
4
from telegram.ext.dispatcher import run_async
5
from telegram.ext import CommandHandler
6
from telegram import ChatAction
7
from pybooru import Moebooru
8
from random import randint
9
import requests
10
import datetime
11
import yaml
12
import os
0 ignored issues
show
Unused Code introduced by
The import os seems to be unused.
Loading history...
13
14
15
def handler(dp):
16
    dp.add_handler(CommandHandler("a", yandere_search, pass_args=True))
17
18
with open("config.yml", "r") as f:
19
    yandere_path = yaml.load(f)["path"]["yandere_search"]
20
21
22
def get_anime(update, query):
23
    update.message.chat.send_action(ChatAction.UPLOAD_PHOTO)
24
    client = Moebooru("yandere")
25
    max_posts_to_load = 200
26
    posts = client.post_list(tags=query, limit=max_posts_to_load)
27
    post_count = len(posts)
28
    random = randint(0, post_count - 1)
29
    image_post = "https://yande.re/post/show/" + str(posts[random]["id"])
30
    image_url = posts[random]["sample_url"]
31
    dl = requests.get(image_url)
32
    with open(yandere_path + "anime_temp.jpg", "wb") as f:
33
        f.write(dl.content)
34
    return image_post
35
36
37
@run_async
38
def yandere_search(bot, update, args):
39
    if args == []:
40
        input_query = "rating:s"
41
    else:
42
        input_query = " ".join(args).lower()
43
    try:
44
        cap = get_anime(update, input_query)
45
        with open(yandere_path + "anime_temp.jpg", "rb") as f:
46
            update.message.reply_photo(f, caption=cap)
47
        print (datetime.datetime.now(),
48
               ">>> Sent anime:", input_query, ">>>",
49
               update.message.from_user.username)
50
    except:
51
        cap = get_anime(update, "rating:s")
52
        with open(yandere_path + "anime_temp.jpg", "rb") as f:
53
            update.message.reply_photo(f, caption="Nothing found, onii-chan, but here's one random pic:\n" + cap)
54
        print (datetime.datetime.now(),
55
               ">>> Tag not found:", input_query, ", sent random", ">>>",
56
               update.message.from_user.username)
57