Completed
Push — master ( 3b8012...1910ba )
by Anas
01:02
created

getgifs()   B

Complexity

Conditions 5

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 5
c 1
b 1
f 0
dl 0
loc 10
rs 8.5454
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ChatAction
4
from telegram.ext import CommandHandler, CallbackQueryHandler
5
from telegram.ext.dispatcher import run_async
6
from random import randint
7
import datetime
8
import yaml
9
import os
10
11
12
def handler(dp):
13
    dp.add_handler(CommandHandler("gif", gif, pass_args=True))
14
    dp.add_handler(CallbackQueryHandler(gif_button, pattern="(gif_)\w+"))
15
16
with open("config.yml", "r") as f:
17
    gif_folder = yaml.load(f)["path"]["gifs"]
18
19
20
@run_async
21
def gif(bot, update, args):
0 ignored issues
show
Unused Code introduced by
The argument bot seems to be unused.
Loading history...
22
    folders = os.walk(gif_folder)
23
    args = "gif_" + str(args)[2:-2]
24
    avail_folders = next(folders)[1]
25
    if args == "gif_help" or args == "gif_?":
26
        reply_markup = make_keyboard(avail_folders)
27
        update.message.reply_text("Available folders for /gif are:", reply_markup=reply_markup)
28
    elif args in avail_folders:
29
        update.message.chat.send_action(ChatAction.UPLOAD_DOCUMENT)
30
        gifs_dir = gif_folder + args
31
        getgifs(update, gifs_dir)
32
    elif args == "gif_":
33
        gifs_dir = gif_folder
34
        getgifs(update, gifs_dir)
35
    else:
36
        update.message.reply_text("No such folder, try /gif help")
37
38
39
def gif_button(bot, update):
40
    query = update.callback_query
41
    user = query.from_user.username
42
    display_data = str(query.data)[4:]
43
    bot.editMessageText(text="%s selected: %s\nUploading can take a while!"
44
                        % (user, display_data),
45
                        chat_id=query.message.chat_id,
46
                        message_id=query.message.message_id)
47
    query.message.chat.send_action(ChatAction.UPLOAD_DOCUMENT)
48
    if display_data == "unsorted":
49
        gifs_dir = gif_folder
50
    else:
51
        gifs_dir = gif_folder + query.data
52
    gifs = [f for f in os.listdir(gifs_dir)
53
            if os.path.isfile(os.path.join(gifs_dir, f))
54
            and f.endswith((".mp4", ".gif"))]
55
    filecount = len(gifs)
56
    rand = randint(0, filecount - 1)
57
    result = list(gifs)[rand]
58
    with open(gifs_dir + "/" + str(result), "rb") as f:
59
        bot.sendDocument(query.message.chat_id, f)
60
    print(datetime.datetime.now(), ">>> Sent gif >>>", query.message.from_user.username, ">", result)
61
62
63
def make_keyboard(folders):
64
    key_list = []
65
    for i in folders:
66
        key = InlineKeyboardButton(str(i)[4:], callback_data=i)
67
        key_list.append(key)
68
    row_split = lambda list, size, acc=[]: (row_split(list[size:], size, acc + [list[:size]]) if list else acc)
69
    rows = row_split(key_list, 4)
70
    root_btn = [InlineKeyboardButton("[unsorted]", callback_data="gif_unsorted")]
71
    rows.insert(0, root_btn)
72
    keyboard = rows
73
    reply_markup = InlineKeyboardMarkup(keyboard)
74
    return reply_markup
75
76
77
def getgifs(update, gifs_dir):
78
    gifs = [f for f in os.listdir(gifs_dir)
79
                    if os.path.isfile(os.path.join(gifs_dir, f))
80
                    and f.endswith((".mp4", ".gif"))]
81
    filecount = len(gifs)
82
    rand = randint(0, filecount - 1)
83
    result = list(gifs)[rand]
84
    with open(gifs_dir + "/" + str(result), "rb") as f:
85
        update.message.reply_document(f)
86
    print(datetime.datetime.now(), ">>> Sent gif >>>", update.message.from_user.username, ">", result)
87