Completed
Push — master ( b37ba4...23c6a9 )
by Anas
32s
created

g_search()   A

Complexity

Conditions 3

Size

Total Lines 15

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 15
rs 9.4285
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
from telegram.ext.dispatcher import run_async
4
from googleapiclient.errors import HttpError
5
from googleapiclient.discovery import build
6
from telegram.ext import CommandHandler
7
from telegram import ChatAction
8
from random import randint
9
import datetime
10
import requests
0 ignored issues
show
Unused Code introduced by
The import requests seems to be unused.
Loading history...
11
import logging
12
import yaml
13
14
logging.getLogger('googleapiclient.discovery').setLevel(logging.ERROR)
15
16
def handler(dp):
17
    dp.add_handler(CommandHandler("img", g_search, pass_args=True))
18
19
with open("config.yml", "r") as f:
20
    yaml_file = yaml.load(f)
21
    dev_key = yaml_file["keys"]["google_dev_key"]
22
    cse_id = yaml_file["keys"]["google_cse_id"]
23
24
25
@run_async
26
def g_search(bot, update, args):
27
    if len(args) == 0:
28
        update.message.reply_text("You need a query to search!")
29
        return
30
    update.message.chat.send_action(ChatAction.UPLOAD_PHOTO)
31
    query = " ".join(args)
32
    try:
33
        final_img = get_image(query)
34
    except HttpError:
35
        update.message.reply_text("Sorry, my daily limit for search exceeded. Check back tomorrow!")
36
        return
37
    msg_text = "[link](%s)" % final_img
38
    update.message.reply_text(msg_text, parse_mode="Markdown")
39
    print (datetime.datetime.now(), ">>>", "Done /img", query, ">>>", update.message.from_user.username)
40
41
42
def get_image(query):
43
    service = build("customsearch", "v1", developerKey=dev_key, cache_discovery=False)
44
    result = service.cse().list(q=query, cx=cse_id, searchType="image").execute()
45
    random_item = randint(0, len(result["items"]))
46
    final_img = result["items"][random_item]["link"]
47
    return final_img
48