Esempio n. 1
0
 async def register(self, ctx, username):
     """register as a member in the league
     Before players can participate in league activities, they must register for the league.
     Upon registration, the player's server nickname will be changed to the one given.
     The player will also be given the Member and Free Agent roles."""
     if username == None:
         await ctx.send("Please provide a username.")
         return
     #check that the desired username is available (not case sensitive)
     database.cur.execute(
         "SELECT * FROM playerTable WHERE lower(username)='%s';" %
         username.lower())
     if database.cur.fetchone() == None:
         await bot.guild.get_member(ctx.author.id).edit(nick=username)
         await ctx.author.add_roles(bot.guild.get_role(bot.MEMBER_ROLE))
         await ctx.author.add_roles(bot.guild.get_role(bot.FREE_AGENT_ROLE))
         utils.escape_string(username)
         database.cur.execute(
             "INSERT INTO playerTable (discordID, username, elo, rep, stats, awards, isprimary) VALUES (%s, '%s', %s, %s, '%s', '{}', false);"
             % (ctx.author.id, username, 1300, 100,
                json.dumps(PLAYER_STATS_DICT)))
         database.conn.commit()
         await ctx.author.send(
             "You have been suggessfully registered. Welcome to CGL!")
         await utils.log("%s registered." % ctx.author.mention)
     else:
         await ctx.send(
             "The username %s is not available. Please choose another one to register for CGL."
             % username)
Esempio n. 2
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)
Esempio n. 3
0
 async def changeteamname(self, ctx, *, teamname):
     #check that the team name is not already taken
     database.cur.execute(
         "SELECT * FROM teamTable WHERE lower(teamname)='%s';" %
         teamname.lower())
     if database.cur.fetchone() != None:
         await ctx.send(
             "The team name '%s' is already taken. Please choose another name."
             % teamname)
         return
     database.cur.execute(
         "SELECT teamname FROM teamTable WHERE captainID=%s;" %
         ctx.author.id)
     team = database.cur.fetchone()[0]
     database.cur.execute(
         "SELECT teamRoleID FROM teamTable WHERE teamname='%s';" % team)
     roleid = database.cur.fetchone()[0]
     teamrole = bot.guild.get_role(roleid)
     await teamrole.edit(name=teamname)
     utils.escape_string(teamname)
     database.cur.execute(
         "UPDATE teamtable SET teamname='%s' WHERE teamname='%s';" %
         (teamname, team))
     database.cur.execute(
         "UPDATE playertable SET team='%s' WHERE team='%s';" %
         (teamname, team))
     database.conn.commit()
     await ctx.send("Your team name has been changed to %s." % teamname)
Esempio n. 4
0
def notify_admin(ex):
    print("Error: {}\nAdmin has been notified".format(ex))
    for admin in cfg.globalCfg.admins:
        bot.send_message(chat_id=admin,
                         text="*Bot error!*\n\n_{}_\n\n{}".format(
                             utils.escape_string(ex.__str__()),
                             utils.escape_string(traceback.format_exc())),
                         parse_mode=telegram.ParseMode.MARKDOWN)
    pass
Esempio n. 5
0
 async def createteam(self, ctx, *, teamname):
     """create a team
     Creates a new team with the given name and makes the user the captain of that team.
     Players may not create a team if they are already a member of another team."""
     #check that the user is not already on a team
     database.cur.execute(
         "SELECT team FROM playerTable WHERE discordID=%s;" % ctx.author.id)
     if database.cur.fetchone()[0] != None:
         await ctx.send(
             "You cannot be on more than one team at a time. Please leave your current team before creating another one."
         )
         return
     if teamname == None:
         await ctx.send("Please provide a team name.")
         return
     if teamname.lower() in PROHIBITED_NAMES:
         await ctx.send("You cannot create a team with that name.")
         return
     #check that the team name is not already taken
     database.cur.execute(
         "SELECT * FROM teamTable WHERE lower(teamname)='%s';" %
         teamname.lower())
     if database.cur.fetchone() != None:
         await ctx.send(
             "The team name '%s' is already taken. Please choose another name."
             % teamname)
         return
     #create the team
     teamrole = await bot.guild.create_role(name=teamname,
                                            colour=discord.Colour.orange(),
                                            hoist=True,
                                            mentionable=True)
     await teamrole.edit(
         permissions=bot.guild.get_role(bot.MEMBER_ROLE).permissions)
     member = bot.guild.get_member(ctx.author.id)
     await member.remove_roles(bot.guild.get_role(bot.FREE_AGENT_ROLE))
     await member.add_roles(teamrole)
     utils.escape_string(teamname)
     captainelo = database.player_elo(ctx.author.id)
     database.cur.execute(
         "INSERT INTO teamTable (teamname, stats, captainID, teamRoleID, awards, elo) VALUES ('%s', '%s', %s, %s, '{}', 1300);"
         % (teamname, json.dumps(TEAM_STATS_DICT), ctx.author.id,
            teamrole.id))
     database.cur.execute(
         "UPDATE playerTable SET team='%s', isprimary=true WHERE discordID=%s;"
         % (teamname, ctx.author.id))
     database.conn.commit()
     await teams.update_elo(teamname)
     await ctx.send(
         "Team \'%s\' successfully created. Invite other players to your team using the !invite command."
         % teamname)
     await utils.log("%s created %s." %
                     (database.username(ctx.author.id), teamname))
     await teams.update_role_position(teamname)
Esempio n. 6
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
Esempio n. 7
0
def update_serialized_option_value(shell, option_table, option_name, expr):
    """
    직렬화 된 값 안에서 문자열은 문자열의 길이를 기억하게 되어 있다. 문자열 치환이 직렬화된 값 안에서 일어났다면 문자열의 길이도 변경해야 한다.

    :param shell:
    :param option_table:
    :param option_name:
    :param expr:
    :return:
    """
    def repl(match):
        return 's:%d:\"%s\";' % (len(match.group(2)), match.group(2))

    query = '"SELECT option_value AS \'\' FROM %s WHERE option_name=\'%s\'"' % (
        option_table, option_name)
    cmd = shell.cmd_mysql(mysql_options='-s -r -e {}'.format(query))
    m = local(cmd, capture=True)

    expr = 's:(\d+):"(%s)";' % expr
    replaced = escape_string(re.sub(expr, repl, m.stdout)).decode('utf-8')

    f = TemporaryFile()
    query = 'UPDATE %s SET option_value=\'%s\' WHERE option_name=\'%s\';' % (
        option_table, replaced, option_name)
    f.write(query)
    f.close()

    local(shell.cmd_mysql() + ' < ' + f.name)
Esempio n. 8
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"
    def __mask_and_write(self, tweet, writer):
        posted_at = str(
            tweet.created_at)  # have to cast cause it's a datetime object
        tweet_id = tweet.id_str
        in_reply_to_tweet_id = tweet.in_reply_to_status_id_str
        in_reply_to_user_id = tweet.in_reply_to_user_id_str
        user_id = tweet.user.id_str
        user_name = tweet.user.name
        user_screen_name = tweet.user.screen_name
        user_verified = 0
        if tweet.user.verified:  # this is to save space
            user_verified = 1
        tweet_text = tweet.text
        tweet_text = escape_string(tweet_text)
        # replies_no = tweet.? #don't think it's in here
        retweets_no = tweet.retweet_count
        likes = tweet.favorite_count
        application_used = tweet.source_url
        # possibly_sensitive = 0
        # if tweet.retweeted_status.possibly_sensitive:
        #    possibly_sensitive = 1
        user_location = tweet.user.location
        coordinates = tweet.coordinates
        user_timezone = tweet.user.time_zone
        follower_count = tweet.user.followers_count
        following_count = tweet.user.friends_count
        user_likes_no = tweet.user.favourites_count
        lang = tweet.lang
        user_created = str(
            tweet.user.created_at)  # have to cast cause it's a datetime object

        writer.writerow({
            "posted_at": posted_at,
            "tweet_id": tweet_id,
            "in_reply_to_tweet_id": in_reply_to_tweet_id,
            "in_reply_to_user_id": in_reply_to_user_id,
            "user_id": user_id,
            "user_name": user_name,
            "user_screen_name": user_screen_name,
            "user_verified": user_verified,
            "tweet_text": tweet_text,
            "retweets_no": retweets_no,
            "likes": likes,
            "application_used": application_used,
            "user_location": user_location,
            "coordinates": coordinates,
            "user_timezone": user_timezone,
            "follower_count": follower_count,
            "following_count": following_count,
            "user_likes_no": user_likes_no,
            "lang": lang,
            "user_created": user_created
        })
Esempio n. 10
0
 async def changename(self, ctx, username):
     """change username"""
     if username == None:
         await ctx.send("Please provide a new username.")
         return
     oldname = database.username(ctx.author.id)
     #check that the desired username is available (not case sensitive)
     database.cur.execute(
         "SELECT * FROM playerTable WHERE lower(username)='%s';" %
         username.lower())
     if database.cur.fetchone() == None:
         await bot.guild.get_member(ctx.author.id).edit(nick=username)
         utils.escape_string(username)
         database.cur.execute(
             "UPDATE playerTable SET username='******' WHERE discordID=%s;" %
             (username, ctx.author.id))
         database.conn.commit()
         await ctx.send("Username successfully changed.")
         await utils.log("%s changed their username to %s." %
                         (oldname, username))
     else:
         await ctx.send(
             "The username %s is not available. Please choose another one to register for CGL."
             % username)
Esempio n. 11
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)
Esempio n. 12
0
 def escapeText(self):
     return utils.escape_string(self.text)
Esempio n. 13
0
 def escapeFText(self):
     return utils.escape_string(self.forwarded_text)
Esempio n. 14
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
Esempio n. 15
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)
Esempio n. 16
0
def copy_from_work_dir(input_file, unescaped_output_path, work_dir="work"):
    input_path = utils.file_to_path(input_file, work_dir=work_dir)
    output_path = utils.escape_string(unescaped_output_path)
    command = f"cp {input_path} {output_path}"
    subprocess.run(command, shell=True, check=True)
    return output_path
Esempio n. 17
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)