Example #1
0
def list(bot, update):

    try:
        user = checkUser(update)
        if (len(user.triggers) == 0):
            bot.send_message(chat_id=update.message.chat_id,
                             text=language.getLang(user.lang)["list_is_empty"],
                             reply_markup={"remove_keyboard": True},
                             reply_to_message_id=update.message.message_id)
            return

        text = language.getLang(user.lang)["list"]
        for x in user.triggers:
            text += language.getLang(user.lang)["list_item"].format(
                utils.escape_string(x["text"]),
                language.getLang(user.lang)["list_item_has_caption"]
                if x["caption"] != None else "",
                language.getLang(user.lang)["list_item_has_attachment"].format(
                    x["attachment"]["type"])
                if x["attachment"] != None else "")

        bot.send_message(chat_id=update.message.chat_id,
                         text=utils.escape_string(text),
                         reply_markup={
                             "remove_keyboard": True,
                             "selective": True
                         },
                         parse_mode=telegram.ParseMode.MARKDOWN,
                         reply_to_message_id=update.message.message_id)

    except Exception as ex:
        notify_admin(ex)
Example #2
0
def unsubscribe(bot, update):
    utils.incStatTG("unsubscribe")

    currentDataPackage = {
        "action" : "unsubscribe",
        "chat_id" : update.message.chat_id,
    }

    try:
        user = db.userHandle.get_user(update.message.chat_id)
        if(len(user.vkGroups) == 0):
            update.message.reply_text(language.getLang(user.lang)["group_list_is_empty"], reply_markup = { "remove_keyboard" : True })
            return
        
        custom_keyboard = []
        for group in user.vkGroups:
            custom_keyboard.append([telegram.KeyboardButton(text=u"{} - {}".format(group["id"], group["name"]))])

        reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
        update.message.reply_text(language.getLang(user.lang)["select_group"], reply_markup=reply_markup)
        user.currListening = 1
        db.userHandle.store_user(user)
    
    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #3
0
def textInputHandler(bot, update):
    utils.incStatTG("_textInput")

    currentDataPackage = {
        "action" : "_textInput",
        "chat_id" : update.message.chat_id,
        "message_text" : update.message.text
    }

    try:
        user = db.userHandle.get_user(update.message.chat_id)
        if(groupRe.search(update.message.text)):

            id = int(update.message.text.split('-')[0].strip())
            name = update.message.text.split('-')[1].strip()
            
            if(any(x["id"] == id for x in user.vkGroups)):
                
                if(user.currListening == 1):
                    
                    user.vkGroups = [x for x in user.vkGroups if x["id"] != id]
                    db.userHandle.store_user(user)
                    bot.send_message(
                        chat_id = update.message.chat_id, 
                        text = language.getLang(user.lang)["succ_removed_url"].format(name, id), 
                        parse_mode = telegram.ParseMode.MARKDOWN,
                        reply_markup = { "remove_keyboard" : True })
                
                elif(user.currListening == 2):
                    
                    bot.send_message(chat_id = update.message.chat_id, text = language.getLang(user.lang)["getting_posts"].format(user.getPosts["count"], name, id), 
                        parse_mode = telegram.ParseMode.MARKDOWN,
                        reply_markup = { "remove_keyboard" : True })

                    posts = vkcore.get_posts(id, True, user.getPosts["count"], user.getPosts["offset"])
                    cfg.globalStat.postSent += len(posts) 
                    cfg.globalStat.postRecieved += len(posts)

                    for post in posts:
                        postSender.send_post(bot, name, id, post, user)
                else:
                    update.message.reply_text(random.choice(language.getLang(user.lang)["group_text_reply"]), reply_markup = { "remove_keyboard" : True })

            else:
                update.message.reply_text(language.getLang(user.lang)["err_unknown_id"], reply_markup = { "remove_keyboard" : True })
                return

            user.currListening = 0
            db.userHandle.store_user(user)

        else:
            update.message.reply_text(random.choice(language.getLang(user.lang)["text_reply"]), reply_markup = { "remove_keyboard" : True })
            return
    
    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #4
0
def subscribe(bot, update):
    utils.incStatTG("subscribe")

    currentDataPackage = {
        "action" : "subscribe",
        "chat_id" : update.message.chat_id,
        "message_text" : update.message.text,
    }

    try:
        user = db.userHandle.get_user(update.message.chat_id)
        url = update.message.text.replace("/subscribe", "").strip()
        id = ""

        if(url == ""):
            update.message.reply_text(language.getLang(user.lang)["err_empty_public_url"], reply_markup = { "remove_keyboard" : True })
            return
        else:
            if(urlRePublicFull.search(url)):
                id = urlRePublicFull.search(url).group()

            elif(urlRePublic.search(url)):
                id = urlRePublic.search(url).group()

            elif(urlRePublicId.search(url)):
                id = urlRePublicId.search(url).group()

            else:
                update.message.reply_text(language.getLang(user.lang)["err_wrong_public_url"], reply_markup = { "remove_keyboard" : True })
                return
        
        info = vkcore.get_group_info(id)

        if(info[0] == ''):
            update.message.reply_text(language.getLang(user.lang)["err_cant_find_url"], reply_markup = { "remove_keyboard" : True })
            return
        
        if(any(x["id"] == info[1] for x in user.vkGroups)):
            update.message.reply_text(language.getLang(user.lang)["err_already_exists_url"], reply_markup = { "remove_keyboard" : True })
            return

        user.vkGroups.append( { "name" : info[0], "id" : info[1] } )
        db.userHandle.store_user(user)
        
        bot.send_message(
            chat_id = update.message.chat_id, 
            text = language.getLang(user.lang)["succ_added_new_url"].format(info[0], info[1]), 
            parse_mode = telegram.ParseMode.MARKDOWN,
            reply_markup = { "remove_keyboard" : True })

    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #5
0
 def wrapped(bot, update, *args, **kwargs):
     user_id = update.effective_user.id
     if user_id not in LIST_OF_ADMINS:
         update.message.reply_text(
             language.getLang("ru")["err_not_allowed"].format(user_id))
         return
     return func(bot, update, *args, **kwargs)
Example #6
0
def adm_db_dump(bot, update, args):
    utils.incStatTG("adm_dump")

    currentDataPackage = {
        "action" : "adm_dump",
        "chat_id" : update.message.chat_id,
    }

    try:
        db.statTimeHandle.store_stat(cfg.globalStat)
        lang = language.getLang(db.userHandle.get_user(update.message.chat_id).lang)

        #print(lang)

        if(len(args) == 0 or args[0] != 't'):
            with open(db.mainDBFileName) as f:
                bot.send_document(chat_id=update.message.chat_id, document=f,
                    caption=lang["dump_file"])

        else:
            with open(db.mainDBFileName) as f:
                data = json.load(f)
                bot.send_message(
                    chat_id = update.message.chat_id, 
                    text = lang["dump_text"].format(json.dumps(data, sort_keys=True, indent=2)),
                    parse_mode = telegram.ParseMode.MARKDOWN,
                    reply_markup = { "remove_keyboard" : True })
        
    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #7
0
def help(bot, update):

    try:
        user = checkUser(update)
        update.message.reply_text(language.getLang(user.lang)["help"],
                                  reply_markup={"remove_keyboard": True})

    except Exception as ex:
        notify_admin(ex)
Example #8
0
def settings(bot, update):
    try:

        group = checkUser(update)
        bot.send_message(chat_id=update.message.chat_id,
                         text=language.getLang(group.lang)["menu"],
                         reply_markup=menuHandler.get_main_menu(group, bot),
                         reply_to_message_id=update.message.message_id)

    except Exception as ex:
        notify_admin(ex)
Example #9
0
def errorHandler(bot, update, error):
    utils.incStatTG("_error")

    try:
        postSender.notify_admin(error)
        #postSender.notify_admin_message(error)
        if(update != None):
            user = db.userHandle.get_user(update.message.chat_id)
            update.message.reply_text(language.getLang(user.lang)["server_error"], reply_markup = { "remove_keyboard" : True })

    except Exception as ex:
        postSender.notify_admin(ex) #No sense to put dataPackage here...
Example #10
0
def getPosts(bot, update):
    utils.incStatTG("getPosts")

    currentDataPackage = {
        "action" : "getPosts",
        "chat_id" : update.message.chat_id,
        "message_text" : update.message.text
    }

    try:
        user = db.userHandle.get_user(update.message.chat_id)
        if(len(user.vkGroups) == 0):
            update.message.reply_text(language.getLang(user.lang)["group_list_is_empty"], reply_markup = { "remove_keyboard" : True })
            return

        parts = [x for x in update.message.text.lower().replace("/getposts", "").strip().split(' ') if x != '']
        count = 5
        offset = 0

        if(len(parts) >= 2):
            count = int(parts[0])
            offset = int(parts[1])
        else:
            if(len(parts) == 1):
                count = int(parts[0])

        custom_keyboard = []
        for group in user.vkGroups:
            custom_keyboard.append([telegram.KeyboardButton(text=u"{} - {}".format(group["id"], group["name"]))])

        user.getPosts = { "count" : count, "offset" : offset }
        user.currListening = 2

        db.userHandle.store_user(user)

        reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
        update.message.reply_text(language.getLang(user.lang)["get_posts"].format(count), reply_markup=reply_markup)

    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #11
0
def disable(bot, update):
    try:
        group = checkUser(update)
        if (not group.enabled):
            bot.send_message(chat_id=update.message.chat_id,
                             text=language.getLang(
                                 group.lang)["err_bot_is_disabled"],
                             reply_markup={"remove_keyboard": True},
                             reply_to_message_id=update.message.message_id)
            return

        group.enabled = False
        db.store_user(group)

        bot.send_message(chat_id=update.message.chat_id,
                         text=language.getLang(group.lang)["bot_disabled"],
                         reply_markup={"remove_keyboard": True},
                         reply_to_message_id=update.message.message_id)
        return

    except Exception as ex:
        notify_admin(ex)
Example #12
0
def settings(bot, update):
    utils.incStatTG("settings")
    
    currentDataPackage = {
        "action" : "settings",
        "chat_id" : update.message.chat_id,
    }

    try:
        user = db.userHandle.get_user(update.message.chat_id)
        bot.send_message(chat_id=user.teleId, text=language.getLang(user.lang)["menu"], reply_markup=menuHandler.get_main_menu(user, bot))
    
    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #13
0
def help(bot, update):
    utils.incStatTG("help")

    currentDataPackage = {
        "action" : "help",
        "chat_id" : update.message.chat_id,
    }

    try:
        user = db.userHandle.get_user(update.message.chat_id)
        update.message.reply_text(language.getLang(user.lang)["help"], reply_markup = { "remove_keyboard" : True })

    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #14
0
def errorHandler(bot, update, error):
    try:
        print(error)
        if (update == None):
            raise TypeError("Update was error. Error is: " + str(error))
        else:

            user = checkUser(update)
            update.message.reply_text(language.getLang(
                user.lang)["server_error"],
                                      reply_markup={"remove_keyboard": True})

    except Exception as ex:
        notify_admin(ex)
Example #15
0
def getGroups(bot, update):
    utils.incStatTG("getGroups")

    currentDataPackage = {
        "action" : "getGroups",
        "chat_id" : update.message.chat_id,
    }

    try:

        #text = "#\n\nAvailable data package: _\n{}_\n".format(utils.escape_string(json.dumps(currentDataPackage, sort_keys=True, indent=2), utils.ef_italic)) if currentDataPackage != None else ""
        #print text
        #bot.send_message(
                #chat_id = update.message.chat_id, 
                #text = text,
                #parse_mode = telegram.ParseMode.MARKDOWN,
                #reply_markup = { "remove_keyboard" : True })  

        #raise TypeError()

        user = db.userHandle.get_user(update.message.chat_id)
        if(len(user.vkGroups) == 0):
            update.message.reply_text(language.getLang(user.lang)["group_list_is_empty"], reply_markup = { "remove_keyboard" : True })
        else:
            text = language.getLang(user.lang)["group_list"] + '\n'
            for group in user.vkGroups:
                text += language.getLang(user.lang)["get_groups"].format(
                    utils.escape_string(group["name"], utils.ef_bold), group["id"])
            
            bot.send_message(
                chat_id = update.message.chat_id, 
                text = text, 
                parse_mode = telegram.ParseMode.MARKDOWN,
                reply_markup = { "remove_keyboard" : True })  

    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #16
0
def get_main_menu(user, bot):
    return telegram.InlineKeyboardMarkup(
        [[
            telegram.InlineKeyboardButton(text=language.getLang(
                user.lang)["menu_lang"],
                                          callback_data="btn_lang")
        ],
         [
             telegram.InlineKeyboardButton(text=language.getLang(
                 user.lang)["menu_ignoreCase"].format(
                     u"โœ…" if user.ignoreCase else u"โ›”๏ธ"),
                                           callback_data="btn_ign")
         ],
         [
             telegram.InlineKeyboardButton(text=language.getLang(
                 user.lang)["menu_admMode"].format(
                     u"โœ…" if user.adminMode else u"โ›”๏ธ"),
                                           callback_data="btn_adm")
         ],
         [
             telegram.InlineKeyboardButton(text=language.getLang(
                 user.lang)["menu_close"],
                                           callback_data="btn_close")
         ]])
Example #17
0
def remove(bot, update):

    try:
        group = checkUser(update)
        user = update.message.from_user

        if (len(group.triggers) == 0):
            bot.send_message(chat_id=update.message.chat_id,
                             text=language.getLang(
                                 group.lang)["list_is_empty"],
                             reply_markup={"remove_keyboard": True},
                             reply_to_message_id=update.message.message_id)
            return

        custom_keyboard = []
        i = 1
        for x in group.triggers:
            custom_keyboard.append([
                telegram.KeyboardButton(
                    text=u"{} - \"{}\"".format(i, x["text"]))
            ])
            i += 1

        bot.send_message(chat_id=update.message.chat_id,
                         text=language.getLang(group.lang)["remove_trigger"],
                         reply_markup=telegram.ReplyKeyboardMarkup(
                             custom_keyboard, resize_keyboard=True),
                         reply_to_message_id=update.message.message_id)

        group.userActions[user.id] = {}
        group.userActions[user.id]["i"] = WAITING_FOR_EX_TRIGGER
        db.store_user(group)
        pass

    except Exception as ex:
        notify_admin(ex)
Example #18
0
def notify_admin(ex, data = None):
    utils.incStatTG("_error_notified")
    
    data=None

    print("Error: {}. Admin has been notified".format(ex))
    for admin in cfg.globalCfg.admins:
        lang = language.getLang(db.userHandle.get_user(admin).lang)
        tgcore.bot.send_message(
            chat_id=admin,
            text=lang["unhandled_error"].format(
                utils.escape_string(ex.__str__(), utils.ef_italic), 
                utils.escape_string(traceback.format_exc()),
                lang["unhandled_error_package"].format(utils.escape_string(json.dumps(data, sort_keys=True, indent=2), utils.ef_italic)) if data != None else ""), 
            parse_mode = telegram.ParseMode.MARKDOWN)
    pass
Example #19
0
def start(bot, update):
    utils.incStatTG("start")

    currentDataPackage = {
        "action" : "start",
        "chat_id" : update.message.chat_id,
    }

    try:
        if(not db.userHandle.has_user(update.message.chat_id)):
            db.userHandle.store_user(dbUser.dbUser(teleid=update.message.chat_id, debugName=update.message.from_user.first_name))

        user = db.userHandle.get_user(update.message.chat_id)
        update.message.reply_text(language.getLang(user.lang)["help"], reply_markup = { "remove_keyboard" : True })
    
    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #20
0
def getText(grName, grId, post, user):
    lang = language.getLang(user.lang)

    text = u""
    if(user.postFormat["show_autor"]):
        text += lang["post_header"].format(utils.escape_string(grName, True))
        if(user.postFormat["show_id"]): text += lang["post_header_id"].format(grId)
        if(user.postFormat["show_link"]): text += lang["post_header_link"].format(grId, post.id)

    if(user.postFormat["show_date"]):
        text += lang["post_header_at"].format(datetime.fromtimestamp(post.date + 3600 * cfg.globalCfg.time_zone).strftime(cfg.globalCfg.time_format))
    
    if(user.postFormat["show_likes"]):
        text += lang["post_header_likes"].format(
            post.likeCount, 
            post.commentsCount, 
            post.repostsCount)

    if(user.postFormat["show_status"]):
        text += lang["post_header_status"].format(
            u'๐Ÿ“Œ' if post.isPinned else ' ',
            u'๐Ÿ’ฐ' if post.isAd else ' ',
            u'โžก๏ธ' if post.isForwarded else ' ')

    if(post.text != ''):
        text += u"\n\n" + makeVKLinks(post.escapeText())

    if(post.forwarded_from_id != 0):

        if(post.forwarded_from_id < 0):
            #sent from group
            _name, _id = vkcore.get_group_info(-post.forwarded_from_id)
            text += lang["forwaded_from"].format(utils.escape_string(_name, utils.ef_bold))
        
        else:
            fname, sname = vkcore.get_user_info(post.forwarded_from_id)
            text += lang["forwaded_from"].format(lang["name_format"].format(
                utils.escape_string(fname, utils.ef_bold),
                utils.escape_string(sname, utils.ef_bold)
            ))

        if(post.forwarded_text != ""):
            text += lang["ori_post_text"].format(makeVKLinks(post.escapeFText()))

    return text + "\n"
Example #21
0
def adm_db_drop(bot, update):
    utils.incStatTG("adm_drop")

    currentDataPackage = {
        "action" : "adm_drop",
        "chat_id" : update.message.chat_id,
    }

    try:
        lang = language.getLang(db.userHandle.get_user(update.message.chat_id).lang)

        bot.send_message(
            chat_id = update.message.chat_id, 
            text = lang["drop_confirm"],
            reply_markup = menuHandler.confirm_drop(lang))

    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #22
0
def add(bot, update):
    try:
        group = checkUser(update)
        user = update.message.from_user

        bot.send_message(chat_id=update.message.chat_id,
                         text=language.getLang(
                             group.lang)["add_enter_regexp"].format(
                                 user.first_name),
                         reply_markup={"remove_keyboard": True},
                         reply_to_message_id=update.message.message_id)

        group.userActions[user.id] = {}
        group.userActions[user.id]["i"] = WAITING_FOR_REGEX
        db.store_user(group)
        pass

    except Exception as ex:
        notify_admin(ex)
Example #23
0
def get_main_menu(user, bot):
    lang = language.getLang(user.lang)
    return telegram.InlineKeyboardMarkup(
        [[
            telegram.InlineKeyboardButton(text=lang["menu_monitoring"].format(
                u'โŒ' if user.ignoreMonitoring else u'โœ…'),
                                          callback_data="btn_monitoring")
        ],
         [
             telegram.InlineKeyboardButton(text=lang["menu_lang"],
                                           callback_data="btn_language")
         ],
         [
             telegram.InlineKeyboardButton(text=lang["menu_postformat"],
                                           callback_data="btn_post_format")
         ],
         [
             telegram.InlineKeyboardButton(text=lang["menu_close"],
                                           callback_data="btn_close")
         ]])
Example #24
0
def adm_stat(bot, update):
    utils.incStatTG("adm_stat")

    currentDataPackage = {
        "action" : "adm_stat",
        "chat_id" : update.message.chat_id,
    }

    try:

        langCode = db.userHandle.get_user(update.message.chat_id).lang
        lang = language.getLang(langCode)
        
        pid = os.getpid()
        py = psutil.Process(pid)
        mem = psutil.virtual_memory()

        bot.send_message(
            chat_id = update.message.chat_id, 
            text = lang["stat"].format(
                    psutil.cpu_percent(), 
                    utils.sizeof_fmt(mem.total), 
                    utils.sizeof_fmt(mem.available), 
                    utils.sizeof_fmt(mem.free), 
                    utils.sizeof_fmt(mem.used), 
                    mem.percent, 
                    language.display_time(time.time() - psutil.boot_time(), langCode, 5), 
                    language.display_time(time.time() - py.create_time(), langCode, 5),
                    cfg.globalStat.postSent,
                    cfg.globalStat.postRecieved,
                    cfg.globalStat.forcedRequests,
                    lang["stat_empty"] if len(cfg.globalStat.postAttachments) == 0 else '\n' + "\n".join([lang["stat_list_item"].format(utils.escape_string(k, utils.ef_bold), utils.escape_string(v, utils.ef_italic)) for k, v in iter(cfg.globalStat.postAttachments.items())]),
                    lang["stat_empty"] if len(cfg.globalStat.vkRequests) == 0 else '\n' +"\n".join([lang["stat_list_item"].format(utils.escape_string(k, utils.ef_bold), utils.escape_string(v, utils.ef_italic)) for k, v in iter(cfg.globalStat.vkRequests.items())]),
                    lang["stat_empty"] if len(cfg.globalStat.tgRequests) == 0 else '\n' +"\n".join([lang["stat_list_item"].format(utils.escape_string(k, utils.ef_bold), utils.escape_string(v, utils.ef_italic)) for k, v in iter(cfg.globalStat.tgRequests.items())])),
            
            parse_mode = telegram.ParseMode.MARKDOWN,
            reply_markup = { "remove_keyboard" : True })
    
    except Exception as ex:
        postSender.notify_admin(ex, currentDataPackage)
Example #25
0
def get_menu(act, user, bot):

    if (act == "btn_tomain" or act == "btn_ign" or act == "btn_adm"):

        if (act == "btn_ign"):
            user.ignoreCase = not user.ignoreCase

        if (act == "btn_adm"):
            user.adminMode = not user.adminMode

        db.store_user(user)
        return get_main_menu(user, bot)

    elif (act == "btn_lang" or act == "btn_ru" or act == "btn_en"):

        if (act == "btn_ru"):
            user.lang = "ru"
            db.store_user(user)

        if (act == "btn_en"):
            user.lang = "en"
            db.store_user(user)

        return telegram.InlineKeyboardMarkup([
            [
                telegram.InlineKeyboardButton(text=language.getLang(
                    user.lang)["menu_ru"].format(u'โœ…' if user.lang ==
                                                 "ru" else u' '),
                                              callback_data="btn_ru")
            ],
            #[telegram.InlineKeyboardButton(text=language.getLang(user.lang)["menu_en"]
            #    .format(u'โœ…' if user.lang == "en" else u' '), callback_data="btn_en")],
            [
                telegram.InlineKeyboardButton(text="ะะฐะทะฐะด",
                                              callback_data="btn_tomain")
            ]
        ])

    if (act == "btn_close"):
        return {}
Example #26
0
def send_post(bot, grName, grId, post, user):
    try:
        maxCaptionLength = 200
        text = getText(grName, grId, post, user)
        id = user.teleId

        if(len(post.attachments) == 1 and post.attachments[0].type == attachmentTypes.photo):
            utils.incAttachments("photo", 1)
            
            bot.send_chat_action(chat_id= id, action=telegram.ChatAction.UPLOAD_PHOTO)
            if(len(text) <= maxCaptionLength):
                bot.send_photo(
                    chat_id = id, 
                    caption = text, 
                    parse_mode = telegram.ParseMode.MARKDOWN, 
                    photo = post.attachments[0].getUrl()['url'],
                    timeout=cfg.globalCfg.sendFileTimeout)

            else:
                bot.send_photo(
                    chat_id = id, 
                    photo = post.attachments[0].getUrl()['url'], 
                    timeout=cfg.globalCfg.sendFileTimeout)
                bot.send_chat_action(chat_id=id, action=telegram.ChatAction.TYPING)
                bot.send_message(chat_id = id, text = text, parse_mode = telegram.ParseMode.MARKDOWN)

        elif(len(post.attachments) == 1 and post.attachments[0].type == attachmentTypes.video):
            utils.incAttachments("video", 1)

            if(post.attachments[0].isYouTube()):
                text += u'\n' + post.attachments[0].getUrl()
                bot.send_message(chat_id = id, text = text, parse_mode = telegram.ParseMode.MARKDOWN)

            else:
                #TODO!
                text += language.getLang(user.lang)["post_video"].format(
                    utils.escape_string(post.attachments[0].title, format=utils.ef_bold),
                    utils.display_time_minimal(post.attachments[0].duration),
                    post.attachments[0].getUrl())

                bot.send_message(chat_id = id, text = text, parse_mode = telegram.ParseMode.MARKDOWN)

                #bot.send_chat_action(chat_id=id, action=telegram.ChatAction.UPLOAD_VIDEO)
                #bot.send_video(chat_id = id, caption = text, parse_mode = telegram.ParseMode.MARKDOWN, video = post.attachments[0].getUrl() )

        elif(len(post.attachments) == 1 and post.attachments[0].type == attachmentTypes.doc):
            utils.incAttachments("doc", 1)

            bot.send_chat_action(chat_id=id, action=telegram.ChatAction.UPLOAD_DOCUMENT)
            if(len(text) <= maxCaptionLength):
                bot.send_document(
                    chat_id = id, 
                    caption = text, 
                    parse_mode = telegram.ParseMode.MARKDOWN, 
                    document = post.attachments[0].url, 
                    filename = post.attachments[0].title,
                    timeout=cfg.globalCfg.sendFileTimeout)

            else:
                bot.send_document(
                    chat_id = id, 
                    document = post.attachments[0].url, 
                    filename = post.attachments[0].title,
                    timeout=cfg.globalCfg.sendFileTimeout)

                bot.send_chat_action(chat_id=id, action=telegram.ChatAction.TYPING)
                bot.send_message(chat_id = id, text = text, parse_mode = telegram.ParseMode.MARKDOWN)

        else:
            
            if(len(post.attachments) != 0):
                for a in [x for x in post.attachments if x.type == attachmentTypes.link]:
                    text += "\n" + a.toMarkdown()
                    utils.incAttachments("link", 1)

                media_group = []
                for a in [x for x in post.attachments if x.type == attachmentTypes.photo]:
                    media_group.append(telegram.InputMediaPhoto(a.getUrl()["url"]))
                    utils.incAttachments("photo", 1)

                for a in [x for x in post.attachments if x.type == attachmentTypes.video]:
                    utils.incAttachments("video", 1)
                    if(a.isYouTube()):
                        text += '\n' + a.getUrl()

                    else:                    
                        text += language.getLang(user.lang)["post_video"].format(
                            utils.escape_string(a.title, utils.ef_bold),
                            utils.display_time_minimal(a.duration),
                            a.getUrl())
                    #media_group.append(telegram.InputMediaVideo(a.getUrl()))
            
                if(len(media_group) != 0):
                    utils.incAttachments("photo", len(media_group))

                    bot.send_chat_action(chat_id=id, action=telegram.ChatAction.UPLOAD_PHOTO)
                    try:
                        bot.send_media_group(
                            chat_id=id, 
                            media=media_group,
                            timeout=cfg.globalCfg.sendFileTimeout)

                    except:
                        print('unable to send media group, trying to download files to disk...')

                        parentDir = os.path.dirname(os.path.realpath(__file__))
                        
                        dirName = u"{}/{}".format(parentDir, "download_data") 
                        
                        try:
                            shutil.rmtree(dirName)
                        except:
                            pass
        
                        os.mkdir(dirName)

                        counter = 0
                        for photoToDownload in [x.media for x in media_group]:
                            
                            r = requests.get(photoToDownload)
                            with open(u'{}/tmp{}.jpg'.format(dirName, counter), 'wb') as f:  
                                f.write(r.content)
                                counter += 1
                            
                        counter = 0
                        nmedia_group = []
                        for photoToDownload in [x.media for x in media_group]:
                            nmedia_group.append(telegram.InputMediaPhoto(open(u'{}/tmp{}.jpg'.format(dirName, counter))))
                            counter += 1

                        try:
                            bot.send_media_group(
                                chat_id=id, 
                                media=nmedia_group,
                                timeout=cfg.globalCfg.sendFileTimeout)

                        except Exception as ex:
                            print(u'still cant send media group =c. {}'.format(ex.message))
                
                for a in [x for x in post.attachments if x.type == attachmentTypes.doc]:
                    utils.incAttachments("doc", 1)
                    
                    bot.send_chat_action(chat_id=id, action=telegram.ChatAction.UPLOAD_DOCUMENT)
                    if(a.ext == 'gif'):
                        bot.send_animation(
                            chat_id = id, 
                            animation = a.url,
                            timeout=cfg.globalCfg.sendFileTimeout)

                    else:
                        bot.send_document(
                            chat_id = id, 
                            document = a.url, 
                            filename = a.title,
                            timeout=cfg.globalCfg.sendFileTimeout)

            bot.send_chat_action(chat_id=id, action=telegram.ChatAction.TYPING)
            bot.send_message(chat_id = id, text = text, parse_mode = telegram.ParseMode.MARKDOWN)
            
    except telegram.utils.request.TimedOut:
        print("Timeout =c")

    pass
Example #27
0
def allInputHandler(bot, update):

    try:
        group = checkUser(update)
        user = update.message.from_user
        textMessage = update.message.text

        if (str(user.id) in group.userActions):

            if (group.userActions[str(user.id)]["i"] == WAITING_FOR_REGEX):

                if (textMessage != '' and utils.isReValid(textMessage)):

                    if (textMessage in [x["text"] for x in group.triggers]):
                        bot.send_message(
                            chat_id=update.message.chat_id,
                            text=utils.escape_string(
                                language.getLang(group.lang)
                                ["err_same_regex_exists"].format(textMessage)),
                            reply_markup={"remove_keyboard": True},
                            parse_mode=telegram.ParseMode.MARKDOWN,
                            reply_to_message_id=update.message.message_id)

                        del group.userActions[str(user.id)]
                        db.store_user(group)
                        return

                    group.userActions[str(user.id)]["r"] = textMessage
                    group.userActions[str(user.id)]["i"] = WAITING_FOR_TRIGGER
                    bot.send_message(
                        chat_id=update.message.chat_id,
                        text=language.getLang(
                            group.lang)["add_enter_sendTrigger"],
                        reply_markup={"remove_keyboard": True},
                        reply_to_message_id=update.message.message_id)

                    db.store_user(group)
                    return
                else:
                    bot.send_message(
                        chat_id=update.message.chat_id,
                        text=utils.escape_string(
                            language.getLang(group.lang)
                            ["err_wrong_regex"].format(textMessage)),
                        reply_markup={"remove_keyboard": True},
                        parse_mode=telegram.ParseMode.MARKDOWN,
                        reply_to_message_id=update.message.message_id)

                    del group.userActions[str(user.id)]
                    db.store_user(group)
                    return

            elif (group.userActions[str(user.id)]["i"] == WAITING_FOR_TRIGGER):

                if (update.message.caption != None):
                    textMessage = update.message.caption

                attachment = None
                if (update.message.photo != None
                        and len(update.message.photo) != 0):
                    attachment = {
                        "file_id": update.message.photo[-1].file_id,
                        "type": "photo"
                    }
                if (update.message.sticker != None):
                    attachment = {
                        "file_id": update.message.sticker.file_id,
                        "type": "sticker"
                    }
                if (update.message.video != None):
                    attachment = {
                        "file_id": update.message.video.file_id,
                        "type": "video"
                    }
                if (update.message.voice != None):
                    attachment = {
                        "file_id": update.message.voice.file_id,
                        "type": "voice"
                    }
                if (update.message.video_note != None):
                    attachment = {
                        "file_id": update.message.video_note.file_id,
                        "type": "video_note"
                    }
                if (update.message.document != None):
                    attachment = {
                        "file_id": update.message.document.file_id,
                        "type": "document"
                    }
                if (update.message.audio != None):
                    attachment = {
                        "file_id": update.message.audio.fild_id,
                        "type": "audio"
                    }
                if (update.message.animation != None):
                    attachment = {
                        "file_id": update.message.animation.file_id,
                        "type": "animation"
                    }

                group.triggers.append({
                    "text":
                    group.userActions[str(user.id)]["r"],
                    "attachment":
                    attachment,
                    "caption":
                    textMessage
                })
                bot.send_message(chat_id=update.message.chat_id,
                                 text=utils.escape_string(
                                     language.getLang(group.lang)["add_ok"]),
                                 reply_markup={"remove_keyboard": True},
                                 parse_mode=telegram.ParseMode.MARKDOWN,
                                 reply_to_message_id=update.message.message_id)

                del group.userActions[str(user.id)]
                db.store_user(group)
                return

            elif (group.userActions[str(
                    user.id)]["i"] == WAITING_FOR_EX_TRIGGER):

                try:
                    parts = textMessage.split('-')[0]
                    index = int(parts) - 1

                    if (index < 0 or index >= len(group.triggers)):
                        bot.send_message(
                            chat_id=update.message.chat_id,
                            text=utils.escape_string(
                                language.getLang(
                                    group.lang)["err_cant_find_item"]),
                            reply_markup={"remove_keyboard": True},
                            reply_to_message_id=update.message.message_id)

                        del group.userActions[str(user.id)]
                        db.store_user(group)
                        return

                    bot.send_message(
                        chat_id=update.message.chat_id,
                        text=utils.escape_string(
                            language.getLang(group.lang)["delete_ok"]),
                        reply_markup={"remove_keyboard": True},
                        reply_to_message_id=update.message.message_id)

                    del group.triggers[index]
                    del group.userActions[str(user.id)]
                    db.store_user(group)

                except IndexError:

                    bot.send_message(
                        chat_id=update.message.chat_id,
                        text=utils.escape_string(
                            language.getLang(
                                group.lang)["err_cant_find_item"]),
                        reply_markup={"remove_keyboard": True},
                        reply_to_message_id=update.message.message_id)

                    del group.userActions[str(user.id)]
                    db.store_user(group)
                    return

                pass

        else:

            if (not group.enabled):
                return

            if (update.message.caption != None):
                textMessage = update.message.caption

            if (textMessage != None):

                for trigger in group.triggers:

                    if (group.ignoreCase):
                        textMessage = textMessage.lower()

                    regex = re.compile(trigger["text"], 0)
                    if (regex.search(textMessage)):

                        if (trigger["attachment"] != None):
                            if (trigger["attachment"]["type"] == "photo"):
                                bot.send_photo(
                                    chat_id=update.message.chat_id,
                                    photo=trigger["attachment"]["file_id"],
                                    reply_to_message_id=update.message.
                                    message_id,
                                    caption=trigger["caption"])

                            elif (trigger["attachment"]["type"] == "sticker"):
                                bot.send_sticker(
                                    chat_id=update.message.chat_id,
                                    sticker=trigger["attachment"]["file_id"],
                                    reply_to_message_id=update.message.
                                    message_id)

                            elif (trigger["attachment"]["type"] == "video"):
                                bot.send_video(
                                    chat_id=update.message.chat_id,
                                    video=trigger["attachment"]["file_id"],
                                    reply_to_message_id=update.message.
                                    message_id,
                                    caption=trigger["caption"])

                            elif (trigger["attachment"]["type"] == "voice"):
                                bot.send_voice(
                                    chat_id=update.message.chat_id,
                                    voice=trigger["attachment"]["file_id"],
                                    reply_to_message_id=update.message.
                                    message_id)

                            elif (trigger["attachment"]["type"] == "document"):
                                bot.send_document(
                                    chat_id=update.message.chat_id,
                                    document=trigger["attachment"]["file_id"],
                                    reply_to_message_id=update.message.
                                    message_id,
                                    caption=trigger["caption"])

                            elif (trigger["attachment"]["type"] == "video_note"
                                  ):
                                bot.send_video_note(
                                    chat_id=update.message.chat_id,
                                    video_note=trigger["attachment"]
                                    ["file_id"],
                                    reply_to_message_id=update.message.
                                    message_id)

                            elif (trigger["attachment"]["type"] == "audio"):
                                bot.send_audio(
                                    chat_id=update.message.chat_id,
                                    audio=trigger["attachment"]["file_id"],
                                    reply_to_message_id=update.message.
                                    message_id,
                                    caption=trigger["caption"])

                            elif (trigger["attachment"]["type"] == "animation"
                                  ):
                                bot.send_animation(
                                    chat_id=update.message.chat_id,
                                    animation=trigger["attachment"]["file_id"],
                                    reply_to_message_id=update.message.
                                    message_id,
                                    caption=trigger["caption"])

                        else:
                            bot.send_message(
                                chat_id=update.message.chat_id,
                                text=trigger["caption"],
                                reply_markup={"remove_keyboard": True},
                                reply_to_message_id=update.message.message_id)

    except Exception as ex:
        notify_admin(ex)
Example #28
0
def get_menu(act, user, bot):
    lang = language.getLang(user.lang)

    if (act == "btn_tomain"):
        return get_main_menu(user, bot)
    if (act in ["btn_language", "btn_ru", "btn_en"]):

        if (act == "btn_ru"):
            user.lang = "ru"
            db.userHandle.store_user(user)
        if (act == "btn_en"):
            user.lang = "en"
            db.userHandle.store_user(user)

        return telegram.InlineKeyboardMarkup([
            [
                telegram.InlineKeyboardButton(text=lang["menu_lang_ru"].format(
                    u'โœ…' if user.lang == "ru" else u' '),
                                              callback_data="btn_ru")
            ],
            [
                telegram.InlineKeyboardButton(text=lang["menu_lang_en"].format(
                    u'โœ…' if user.lang == "en" else u' '),
                                              callback_data="btn_en")
            ],
            [
                telegram.InlineKeyboardButton(text=lang["menu_lang_back"],
                                              callback_data="btn_tomain")
            ]
        ])

    if (act == "btn_monitoring"):
        user.ignoreMonitoring = not user.ignoreMonitoring
        db.userHandle.store_user(user)
        return get_main_menu(user, bot)

    if (act in [
            "btn_post_format", "btn_post_id", "btn_post_date",
            "btn_post_likes", "btn_post_status", "btn_post_link", "btn_autor"
    ]):

        if (act == "btn_post_id"):
            user.postFormat['show_id'] = not user.postFormat['show_id']
            db.userHandle.store_user(user)

        if (act == "btn_post_date"):
            user.postFormat['show_date'] = not user.postFormat['show_date']
            db.userHandle.store_user(user)

        if (act == "btn_post_likes"):
            user.postFormat['show_likes'] = not user.postFormat['show_likes']
            db.userHandle.store_user(user)

        if (act == "btn_post_status"):
            user.postFormat['show_status'] = not user.postFormat['show_status']
            db.userHandle.store_user(user)

        if (act == "btn_autor"):
            user.postFormat['show_autor'] = not user.postFormat['show_autor']
            db.userHandle.store_user(user)

        if (act == "btn_post_link"):
            user.postFormat['show_link'] = not user.postFormat['show_link']
            db.userHandle.store_user(user)

        return telegram.InlineKeyboardMarkup(
            [[
                telegram.InlineKeyboardButton(
                    text=lang["menu_format_id"].format(
                        u'โœ…' if user.postFormat['show_id'] else u'โŒ'),
                    callback_data="btn_post_id")
            ],
             [
                 telegram.InlineKeyboardButton(
                     text=lang["menu_format_date"].format(
                         u'โœ…' if user.postFormat['show_date'] else u'โŒ'),
                     callback_data="btn_post_date")
             ],
             [
                 telegram.InlineKeyboardButton(
                     text=lang["menu_format_likes"].format(
                         u'โœ…' if user.postFormat['show_likes'] else u'โŒ'),
                     callback_data="btn_post_likes")
             ],
             [
                 telegram.InlineKeyboardButton(
                     text=lang["menu_format_status"].format(
                         u'โœ…' if user.postFormat['show_status'] else u'โŒ'),
                     callback_data="btn_post_status")
             ],
             [
                 telegram.InlineKeyboardButton(
                     text=lang["menu_format_link"].format(
                         u'โœ…' if user.postFormat['show_link'] else u'โŒ'),
                     callback_data="btn_post_link")
             ],
             [
                 telegram.InlineKeyboardButton(
                     text=lang["menu_format_autor"].format(
                         u'โœ…' if user.postFormat['show_autor'] else u'โŒ'),
                     callback_data="btn_autor")
             ],
             [
                 telegram.InlineKeyboardButton(text=lang["menu_format_close"],
                                               callback_data="btn_tomain")
             ]])

    if (act == "btn_close" or act == "adm_drop_cancel"):
        return {}

    if (act == "adm_drop"):
        db.userHandle.drop(user.teleId)
        bot.send_message(chat_id=user.teleId, text=lang['dropped'])
        return {}