def update_graffiti(key, data):
     # data must be a dictionary
     if isinstance(data, dict):
         db.update(Graffiti.entry, key, data)
         return Graffiti.get_by_key(key)
     else:
         return None
Example #2
0
    def set(self, update, content):
        try:
            admin = update.message.chat_id
            channel = None

            if len(content.args) == 1:
                channel = db.find("channel", admin=admin)
            elif len(content.args) == 2:
                name = content.args[1]
                channel = db.find("channel", admin=admin, name=name)

            if isinstance(channel, db.Channel):
                state = dict([("off", False),
                              ("on", True)]).get(content.args[0].lower(), None)
                if state is not None:
                    channel.up = state
                    db.update(channel)
                    self.updater.bot.send_message(
                        chat_id=update.message.chat_id,
                        text=strings.up(state=state))
                    logging.info("set: channel {} {}".format(
                        channel.name, content.args[0]))

            elif isinstance(channel, list):
                self.updater.bot.send_message(
                    chat_id=admin,
                    text=
                    "شما صاحب چندین نسخه از بات هستید لطفا نام کانال خود را نیز وارد کنید"
                    "مثال:\n"
                    "/set off @channel",
                    reply_to_message_id=update.message.message_id)

        except Exception as E:
            logging.error("set: {}".format(E))
 def update_user_leisure(key, data):
     # data must be a dictionary
     if isinstance(data, dict):
         db.update(UserLeisure.entry, key, data)
         return UserLeisure.get_by_key(key)
     else:
         return None
Example #4
0
 def change_display_name(key, data):
     # data must be a dictionary
     if isinstance(data, dict):
         db.update(User.entry, key, data)
         return User.get_by_uid(key)
     else:
         return None
Example #5
0
def set_logo(update, content):
    try:
        if update.callback_query:
            um = update.callback_query
            comm, name = um.data.split(';')
            chat_id = um.message.chat_id
            channel = db.find('channel', admin=chat_id, name=name)
            editor.logo_by_name(channel)
            channel.logo = False

            text, keyboard = strings.set_logo_ok(channel=channel)
            content.bot.send_photo(chat_id=chat_id,
                                   reply_to_message_id=um.message.message_id,
                                   photo=open('info.png', 'rb'),
                                   caption=text,
                                   reply_markup=keyboard)
            return set_pos

        elif update.message.sticker:
            print(update.message.sticker)
        elif update.message.document:
            um = update.message
            chat_id = um.chat_id
            file_id = um.document.file_id
            mime = um.document.mime_type
            size = um.document.file_size
            name = um.caption if um.caption else None
            if name:
                res = db.find('channel', admin=chat_id, name=name)
            else:
                res = db.find('channel', admin=chat_id)
            if isinstance(res, db.Channel) and mime.startswith(
                    'image') and size < (8 * 1025 * 1024):
                channel = res
                content.bot.get_file(file_id=file_id).download(
                    'logo/{}.png'.format(channel.name))
                channel.logo = True
                db.update(channel)

                text, keyboard = strings.set_logo_ok(channel=channel)
                content.bot.send_photo(chat_id=chat_id,
                                       reply_to_message_id=um.message_id,
                                       photo=open('info.png', 'rb'),
                                       caption=text,
                                       reply_markup=keyboard)
                return set_pos

            elif isinstance(res, list):
                content.bot.send_message(chat_id=chat_id,
                                         reply_to_message_id=um.message_id,
                                         text=strings.set_logo_fail)
                return set_logo
            else:
                content.bot.send_message(chat_id=chat_id,
                                         reply_to_message_id=um.message_id,
                                         text=strings.set_logo_else)
                return set_logo
    except Exception as E:
        logging.error("set_logo {}".format(E))
Example #6
0
 def insert_into_db(self, table):
     links = self.parse_response()
     print("links", links)
     queries = [self.link_to_insert_request(link, table) for link in links]
     print("queries", queries)
     for q in queries:
         print("insert appart in db")
         update(q)
Example #7
0
 def update_rating(key, data):
     # data must be a dictionary
     if isinstance(data, dict):
         db.update(Rating.entry, key, data)
         return Rating.get_by_key(key)
         # return Rating(key=key, grade=data['grade'], description=data['description'], n_likes=data['n_likes'], leisure=data['leisure'], user=data['user'])
     else:
         return None
 def save_data(self, items):
     if not items:
         return
     with db.transaction():
         for item in items:
             sql = "replace into des_entities (" + db.format_with_separator(
                 item.iterkeys()) + ") values ("
             l = []
             for i in range(0, len(item.keys())):
                 l.append('?')
             sql = sql + db.format_with_separator(l) + ")"
             db.update(sql, *item.values())
Example #9
0
    def update_relation(self, relation_id, info_dict, isSchoolAgent=False):
        """
        更新已经存在的联系
        :param relation_id: 联系的id
        :param info_dict: 要更新的数据,为字典,键表示数据库名;值为要更新的值
        :param isSchoolAgent: 是否是学校商务操作
        :return: 影响的行数
        """
        values = ['%s=?' % key for key in info_dict.keys()]
        params = ','.join(values)

        string = 'update sys_net_of_school_agent set {params} where ID = ?'

        # 企商操作,更换数据库
        if not isSchoolAgent:
            string = 'update sys_net_of_business_agent set {params} where ID = ?'

        sql = string.format(params=params)

        # 将字典转为列表, 目的是 保证将 relation_id 放于最后
        data = list(info_dict.values())
        # 添加 relation_id 于列表最后
        data.append(relation_id)

        return db.update(sql, *data)
def putReminder(id,prop):
    try:
        updateid=db.update('reminder',where='reminderid=$reminderid',vars={'reminderid': id},**prop)
    except:
        t.rollback()
        raise
    else:
        t.commit()
        return updateid
Example #11
0
def set_pos(update, content):
    try:
        um = update.callback_query
        admin = um.message.chat_id
        data = um.data
        pos, name = data.split(';')
        channel = db.find("channel", admin=admin, name=name)
        channel.pos = int(pos)
        db.update(channel)
        content.bot.send_message(chat_id=admin,
                                 reply_to_message_id=um.message.message_id,
                                 text="تغییرات اعمال شد",
                                 reply_markup=InlineKeyboardMarkup([[
                                     Inline('وضعیت',
                                            callback_data='{};{}'.format(
                                                admin, name))
                                 ]]))
        return setting
    except Exception as E:
        logging.error("set_pos {}".format(E))
Example #12
0
def putEvent(id, prop):
    try:
        updateid = db.update('event',
                             where='eventid=$eventid',
                             vars={'eventid': id},
                             **prop)
    except:
        t.rollback()
        raise
    else:
        t.commit()
        return updateid
Example #13
0
 def start(self):
     '''
     启动任务
     :return:
     '''
     try:
         db.update('update des_task set status=? where id=?', 1,
                   self.task_info.id)
         result = self.process()
         if result:
             db.update('update des_task set status=? where id=?', 2,
                       self.task_info.id)
         else:
             db.update('update des_task set status=? where id=?', 3,
                       self.task_info.id)
     except:
         traceback.print_exc()
         log_util.error(traceback.format_exc())
         db.update('update des_task set status=? where id=?', 3,
                   self.task_info.id)
Example #14
0
def done(update, content):
    try:
        if update.callback_query:
            um = update.callback_query
            data = um.data
            part1, channel_name = data.split(';')
            chat_id = um.message.chat_id
            message_id = um.message.message_id

            channel = db.find('channel', name=channel_name)

            if part1 == '_':
                pass
            elif part1.endswith('b'):
                bed = part1[:-1]
                channel.bed = int(bed)
                db.update(channel)
            elif part1.endswith('w'):
                wake = part1[:-1]
                channel.wake = int(wake)
                db.update(channel)
            elif part1.endswith("r") or part1.endswith("f"):
                interval = part1
                channel.interval = interval
                db.update(channel)
            elif part1 == "off":
                channel.bed = -1
                channel.wake = -1
                db.update(channel)

            text, keyboard = strings.status(
                channel=channel, remain=util.remain(channel=channel))
            content.bot.edit_message_text(chat_id=chat_id,
                                          message_id=message_id,
                                          text=text,
                                          reply_markup=keyboard)
            return select

    except Exception as E:
        logging.error("done {}".format(E))
Example #15
0
def start_spider(template_id):
    user = '******'
    pw = 'iwant@201506'
    host = '10.10.139.235'
    port = 3306
    database = 'iwant'
    db.create_engine(user, pw, database, host, port)

    data_source = db.select_one('select id,spider_name,domain,classify,subclass,site,source,des_tasks from des_template where id = ?', template_id)
    if not data_source:
        return
    tasks = json.loads(data_source.des_tasks)
    db.update('update des_task set status=? where id=?', 1, tasks['page_crawl'])
    try:
        process = CrawlerProcess(get_project_settings())

        # 'followall' is the name of one of the spiders of the project.
        process.crawl(data_source.spider_name,**data_source)
        process.start()  # the script will block here until the crawling is finished
    except:
        db.update('update des_task set status=? where id=?', 3, tasks['page_crawl'])

    db.update('update des_task set status=? where id=?', 2, tasks['page_crawl'])
Example #16
0
    def save(self, update, content):
        try:
            um = update.message
            ue = update.edited_message
            message = None
            # edited
            if ue:
                from_gp = ue.chat_id
                msg_gp_id = ue.message_id
                # channel = db.find('channel', group_id=from_gp)
                message = db.find('message',
                                  msg_gp_id=msg_gp_id,
                                  gp_id=from_gp)
                if isinstance(message, db.Message):
                    if ue.reply_to_message:
                        if ue.text:
                            message = db.find(
                                "message",
                                msg_gp_id=ue.reply_to_message.message_id,
                                gp_id=ue.chat_id)
                            if isinstance(message, db.Message):
                                if message.other.isnumeric():
                                    message = db.find("message",
                                                      media=message.other)
                                    for msg in message:
                                        msg.txt = ue.text
                                        db.update(msg)
                                else:
                                    message.txt = ue.text
                                    db.update(message)

                    # # after sent
                    # elif ue.text and message.sent:
                    #     message.txt = editor.id_remove(text=ue.text, channel=channel)
                    #     if len(um.entities) > 0:
                    #         entities = um.entities
                    #         url = ''.join([entities[i].url if entities[i].url else '' for i in range(len(entities))])
                    #         message.txt += '\n<a href="{}">​​​​​​​​​​​</a>'.format(url)
                    #         message.other = 'url'
                    #     parse_mode = 'HTML' if message.other == 'url' else None
                    #     self.robot.edit_message_text(chat_id=message.to_channel, message_id=message.msg_ch_id,
                    #                                  text=message.txt, parse_mode=parse_mode)
                    #     message.sent = message.ch_a = True
                    # elif message.sent:
                    #     media = out = None
                    #     text = ue.caption if ue.caption else ' '
                    #     text = editor.id_remove(text=text, channel=channel)
                    #
                    #     if ue.photo:
                    #         media = ue.photo[-1].file_id
                    #         dir_ = "image/{}.jpg".format(channel.name)
                    #         out = 'image/{}_out.jpg'.format(channel.name)
                    #         self.robot.getFile(media).download(dir_)
                    #
                    #         message.kind = "photo"
                    #         if channel.plan >= 1:
                    #             text = editor.image_watermark(photo=dir_, out=out, caption=text, channel=channel)
                    #             media = telegram.InputMediaPhoto(media=open(out, 'rb'), caption=text)
                    #         else:
                    #             text = editor.id_remove(text=text, channel=channel)
                    #             media = telegram.InputMediaPhoto(media=media, caption=text)
                    #
                    #     elif ue.animation:
                    #         media = ue.animation.file_id
                    #         mime = str(um.animation.mime_type).split('/')[1]
                    #         dir_ = "gif/{}.{}".format(channel.name, mime)
                    #         out = "gif/{}_out.mp4".format(channel.name)
                    #         size = ue.video.file_size / (1024 ** 2)
                    #
                    #         message.mime = mime
                    #         message.kind = 'animation'
                    #
                    #         if size <= limit_size and channel.plan >= 2:
                    #             self.robot.getFile(media).download(dir_)
                    #             text = editor.vid_watermark(vid=dir_, out=out, kind=message.kind,
                    #                                         caption=text, channel=channel)
                    #             media = telegram.InputMediaVideo(media=open(out, 'rb'), caption=text)
                    #         else:
                    #             text = editor.id_remove(text=text, channel=channel)
                    #             media = telegram.InputMediaAnimation(media=media, caption=text)
                    #
                    #     elif ue.video:
                    #         media = ue.video.file_id
                    #         mime = str(um.video.mime_type).split('/')[1]
                    #         dir_ = "vid/{}.{}".format(channel.name, mime)
                    #         out = 'vid/{}_out.mp4'.format(channel.name)
                    #         size = ue.video.file_size / (1024 ** 2)
                    #
                    #         message.mime = mime
                    #         message.kind = 'video'
                    #
                    #         if size < limit_size and channel.plan >= 3:
                    #             self.robot.getFile(media).download(dir_)
                    #             text = editor.vid_watermark(vid=dir_, out=out, kind=message.kind,
                    #                                         caption=text, channel=channel)
                    #             media = telegram.InputMediaVideo(media=open(out, 'rb'), caption=text)
                    #         else:
                    #             text = editor.id_remove(text=text, channel=channel)
                    #             media = telegram.InputMediaVideo(media=media, caption=text)
                    #
                    #     elif ue.document:
                    #         media = ue.document.file_id
                    #         media = telegram.InputMediaDocument(media=media, caption=text)
                    #
                    #     elif ue.audio:
                    #         media = ue.audio.file_id
                    #         media = telegram.InputMediaAudio(media=media, caption=text)
                    #
                    #     if media:
                    #         self.robot.edit_message_media(media=media, chat_id=message.to_channel,
                    #                                       message_id=message.msg_ch_id, timeout=time_out)
                    #
                    #     if out:
                    #         os.remove(out)
                    #     if ue.caption:
                    #         self.robot.edit_message_caption(chat_id=message.to_channel, message_id=message.msg_ch_id,
                    #                                         caption=text)
                    #
                    #     message.sent = message.ch_a = True
                    #     message.txt = text

                    # before sent
                    elif ue.text:
                        message.txt = ue.text
                        message.sent = message.ch_a = False
                        if len(um.entities) > 0:
                            entities = um.entities
                            url = ''.join([
                                entities[i].url if entities[i].url else ''
                                for i in range(len(entities))
                            ])
                            message.txt += '\n<a href="{}">​​​​​​​​​​​</a>'.format(
                                url)
                            message.other = 'url'
                    elif ue.caption:
                        message.txt = ue.caption if ue.caption else " "
                        message.sent = message.ch_a = False
                        if ue.photo:
                            message.kind = 'photo'
                            message.file_id = ue.photo[-1].file_id
                        elif ue.video:
                            message.kind = 'video'
                            message.file_id = ue.video.file_id
                        elif ue.animation:
                            message.kind = 'animation'
                            message.file_id = ue.animation.file_id
                        elif ue.document:
                            message.kind = 'document'
                            message.file_id = ue.document.file_id
                        elif ue.audio:
                            message.kind = 'audio'
                            message.file_id = ue.audio.file_id
                    db.update(message)

            # regular
            elif um:
                channel = db.find(table="channel", group_id=um.chat_id)
                if um.reply_to_message:
                    if um.text:
                        message = db.find(
                            "message",
                            msg_gp_id=um.reply_to_message.message_id,
                            gp_id=um.chat_id)
                        if message.other.isnumeric():
                            message = db.find("message", media=message.other)
                            for msg in message:
                                msg.txt = um.text
                                db.update(msg)
                        else:
                            message.txt = um.text
                            db.update(message)

                elif um.text:
                    other = ""
                    txt = um.text
                    if len(um.entities) > 0:
                        entities = um.entities
                        url = ''.join([
                            entities[i].url if entities[i].url else ''
                            for i in range(len(entities))
                        ])
                        txt += '\n<a href="{}">​​​​​​​​​​​</a>'.format(url)
                        other = 'url'
                    message = db.Message(from_group=um.chat_id,
                                         to_channel=channel.name,
                                         kind='text',
                                         msg_gp_id=um.message_id,
                                         txt=txt,
                                         other=other)
                    db.add(message)
                else:
                    text = um.caption if um.caption else ' '
                    file_id = kind = other = mime = ''
                    size = 0
                    if um.media_group_id:
                        if um.photo:
                            kind = 'photo'
                            file_id = um.photo[-1].file_id
                        elif um.video:
                            kind = 'video'
                            file_id = um.video.file_id
                        other = um.media_group_id
                    elif um.photo:
                        kind = 'photo'
                        file_id = um.photo[-1].file_id
                    elif um.video:
                        kind = 'video'
                        size = um.video.file_size / (1024**2)
                        mime = str(um.video.mime_type).split('/')[1]
                        file_id = um.video.file_id
                    elif um.animation:
                        kind = 'animation'
                        size = um.animation.file_size / (1024**2)
                        mime = str(um.document.mime_type).split('/')[1]
                        file_id = um.document.file_id
                    elif um.document:
                        kind = 'document'
                        file_id = um.document.file_id
                    elif um.voice:
                        kind = 'voice'
                        file_id = um.voice.file_id
                    elif um.audio:
                        kind = 'audio'
                        file_id = um.audio.file_id
                    elif um.video_note:
                        kind = 'v_note'
                        file_id = um.video_note.file_id
                    elif um.sticker:
                        kind = 'sticker'
                        file_id = um.sticker.file_id

                    message = db.Message(from_group=um.chat_id,
                                         to_channel=channel.name,
                                         msg_gp_id=um.message_id,
                                         kind=kind,
                                         txt=text,
                                         file_id=file_id,
                                         size=size,
                                         mime=mime,
                                         other=other)
                    db.add(message)

            if isinstance(message, db.Message):
                logging.info("save {}".format(message.__str__()))
        except Exception as E:
            logging.error('save {}'.format(E))
Example #17
0
    def admin(self, update, content):
        try:
            chat_id = update.message.chat_id
            message_id = update.message.message_id
            command = group_id = admin = channel_name = plan = expire = None
            if content.args:
                self.updater.bot.send_chat_action(
                    chat_id=chat_id, action=telegram.ChatAction.TYPING)
                command = content.args[0]
                if command == "add":
                    group_id, admin, channel_name, plan, expire = content.args[
                        1:]
                    if not db.find('channel', name=channel_name):
                        channel = db.Channel(
                            name=channel_name,
                            admin=int(admin),
                            group_id=int(group_id),
                            plan=int(plan),
                            expire=timedelta(days=int(expire)))
                        db.add(channel)
                        self.updater.bot.send_message(
                            chat_id=chat_id,
                            reply_to_message_id=message_id,
                            text="ثبت شد \n\n{}".format(channel.__str__()))
                elif command == "ren":
                    channel_name, expire = content.args[1:]
                    if db.find("channel", name=channel_name):
                        channel = db.find("channel", name=channel_name)
                        channel.expire += timedelta(days=int(expire))
                        db.update(channel)
                        self.updater.bot.send_message(
                            chat_id=chat_id,
                            reply_to_message_id=message_id,
                            text="ثبت شد \n\n{}".format(channel.__str__()))
                elif command == "plan":
                    channel_name, plan = content.args[1:]
                    channel = db.find("channel", name=channel_name)
                    channel.plan = int(plan)
                    db.update(channel)
                    self.updater.bot.send_message(
                        chat_id=chat_id,
                        reply_to_message_id=message_id,
                        text="ثبت شد \n\n{}".format(channel.__str__()))
                elif command == "del":
                    channel_name = content.args[1]
                    channel = db.find("channel", name=channel_name)
                    if channel:
                        db.delete(channel)
                elif command == "edit":
                    channel_name, n_channel_name = content.args[1:]
                    channel = db.find("channel", name=channel_name)
                    if channel:
                        channel.name = n_channel_name
                        db.update(channel)
                        self.updater.bot.send_message(
                            chat_id=chat_id,
                            reply_to_message_id=message_id,
                            text="ثبت شد \n\n{}".format(channel.__str__()))
                elif command == "lst":
                    channels = db.find('channel')
                    text = "channel          expire_date\n"
                    for ch in channels:
                        expire = JalaliDatetime().from_date(ch.expire)
                        now = JalaliDatetime().now()
                        diff = expire - now
                        if diff.days < 7:
                            text += "{} {} 🔴\n\n".format(
                                ch.name, expire.strftime("%A %d %B"))
                        else:
                            text += "{} {} ⚪️\n\n".format(
                                ch.name, expire.strftime("%A %d %B"))

                    self.updater.bot.send_message(chat_id=cna, text=text)
                elif command == "det":
                    channel_name, = content.args[1:]
                    channel = db.find("channel", name=channel_name)
                    if isinstance(channel, db.Channel):
                        self.updater.bot.send_message(
                            chat_id=chat_id,
                            reply_to_message_id=message_id,
                            text=strings.status(channel,
                                                util.remain(channel),
                                                button=False))
                elif command == "db":
                    # db
                    self.updater.bot.send_document(chat_id=cna,
                                                   document=open(
                                                       "bot_db.db", "rb"),
                                                   timeout=time_out)
                else:
                    self.updater.bot.send_message(
                        chat_id=chat_id,
                        reply_to_message_id=message_id,
                        text="command {} not found".format(content.args[0]))

            else:
                self.updater.bot.send_message(chat_id=chat_id,
                                              text=strings.admin_hint)
        except Exception as E:
            logging.error("admin: {}".format(E))
Example #18
0
 async def update(self, ctx, *args, **kwargs):
     db.update(*args, **kwargs)
     await ctx.done("Finished")
Example #19
0
    async def format_new(self, ctx):
        if await ctx.confirm(**em("React with :thumbsup: to confirm!",
                                  "Would you like to create a new format?",
                                  "info",
                                  icon="null")):
            format_channel = await ctx.ask_channel(
                title="What channel do you want the format to take effect in?")
            n, m = await ctx.emoji_choice(
                {
                    "1\N{combining enclosing keycap}": 1,
                    "2\N{combining enclosing keycap}": 2,
                    "3\N{combining enclosing keycap}": 2,
                    "4\N{combining enclosing keycap}": 4,
                    "5\N{combining enclosing keycap}": 5
                },
                **em("Right now you can choose up to 5 only.",
                     "How many variables do you want to use for this format?",
                     "info"))
            while True:
                vs = []
                for i in range(int(n)):
                    x = await ctx.question(
                        title="What should we use as this variable",
                        description=
                        f"This should be short, eg '{random.choice(['title','text','user','suggestion'])}''"
                    )
                    if x.content in vs and x.content in [
                            "user", "1", "2", "3", "4", "5"
                    ]:
                        raise commands.CommandError(
                            "You cant use the same variable 2 times.")
                    vs.append(x.content)
                example = "```"
                for var in vs:
                    example += "[" + var + "] <insert text here>\n"
                example += "```"
                if await ctx.confirm(**em(f"Please confirm. {example}",
                                          "This is how it will look like.",
                                          type="info")):
                    break
            n, m = await ctx.emoji_choice(
                {
                    "1\N{combining enclosing keycap}": 1,
                    "2\N{combining enclosing keycap}": 2,
                    "3\N{combining enclosing keycap}": 2,
                    "4\N{combining enclosing keycap}": 4,
                    "5\N{combining enclosing keycap}": 5
                },
                **em("Right now you can choose up to 5 only.",
                     "How many actions do you want to do after this format?",
                     "info"))
            while True:
                actions = []
                for i in range(n):
                    y = {
                        "➕": "create_channel",
                        "💬": "send_message",
                        "🙂": "add_reaction",
                        "📝": "add_role"
                    }
                    embed = em("You can choose only one at the time",
                               "Choose an action", "info")["embed"]
                    for x in y:

                        embed.add_field(
                            name=x + " " + y[x],
                            value=f"Do this action by adding the {x} reaction")

                    action, m = await ctx.emoji_choice(y, embed=embed)
                    if action is "create_channel":
                        action = {"name": action}

                        cat = await ctx.question(
                            description=
                            "Please get the exact name of the category the channel should go to.",
                            title=
                            "What is the category the channel should go to.")
                        cat = utils.get(ctx.guild.categories, name=cat.content)
                        if cat is None:
                            raise commands.CommandError("Invalid Category")
                        x = ""
                        for var in vs:
                            x += f"${var} | The variable that was inputed for [{var}]\n"
                        name = await ctx.question(
                            title="What should be the name of the channel",
                            description=
                            "Placeholders:```{number} | the number of times this format has been done\n"
                            + x +
                            "{user} | The author of the message\n{user.mention} | Mentions the user\n{user.name} | the name of the author```"
                        )
                        if await ctx.confirm(**em(
                                "React with a :thumbsup: if you want to set the topic.",
                                "Do you want to have a topic")):
                            x = await ctx.question(
                                title="What should the topic be?",
                                description=
                                "You can use the same placeholders as before.")
                            action["kwargs"]["topic"] = x.content
                        var = i
                        action["args"] = [name]
                        actions.append(actions)
                        await ctx.info("")
                    if action is "send_message":
                        action = {"name": action}
                        await ctx.info(
                            "Mention a channel, use 'self' as the current channel or say the name of a variable before (create_channel actions only)",
                            "Choose a channel to send the message to",
                            icon="null")

                        def check(m):
                            return ctx.channel == m.channel and m.author.id == ctx.author.id

                        try:
                            m = await self.bot.wait_for("message",
                                                        check=check,
                                                        timeout=60)
                        except TimeoutError:
                            raise commands.CommandError("Timed out!")
                        try:
                            x = int(m.content)
                        except:
                            x = 0
                        channel = None
                        if channel is "self":
                            channel = format_channel
                        if x in range(i - 1) and not i >= 1 and actions[
                                x - 1]["name"] is "create_channel":
                            channel = x
                        else:
                            for channel in ctx.guild.text_channels:
                                if len(str(m.content).split(str(
                                        channel.id))) >= 2:
                                    action["channel"] = channel.id

                        if channel is None:
                            raise commands.CommandError(
                                "That is not a channel!")
                        t = await ctx.question(
                            title="What should the title for this message be",
                            description=
                            "This here is a description above is the title")
                        d = await ctx.question(
                            title=
                            "What should the description for this message be",
                            description=
                            "This here is a description above is the title")
                        action["kwargs"] = em(d, t, "info", icon="null")
                        action["args"] = []
                        actions.append(action)
                if await ctx.confirm(
                        **em(str(actions), "Do you wish to use this", "info")):
                    break
            await ctx.send("done")
            data = {
                "channel": format_channel.id,
                "guild": ctx.guild.id,
                "variables": vs,
                "example": example,
                "number": 0,
                "actions": actions
            }
            db.update("formats", f"{ctx.guild.id}-{format_channel.id}", data)

            await ctx.info(f"Its a work in progress. {channel.mention} {vs}")
        else:
            await ctx.error("Process Cancelled", "Cancelled.")
Example #20
0
def insert_subscribers(id):
    query = "insert or ignore into subscribers (id) values ('%s')" % id
    update(query)
Example #21
0
    def send_to_ch(self, channel):
        message = db.get_last_msg(channel_name=channel.name)
        dir_ = out = None
        try:
            # media_group
            if isinstance(message, list):
                chat_id = channel.name
                media = []
                new_message = []
                for msg in message:
                    txt = editor.id_remove(text=msg.txt, channel=channel)
                    if msg.kind == 'photo':
                        media.append(
                            telegram.InputMediaPhoto(media=msg.file_id,
                                                     caption=txt))
                    elif msg.kind == 'video':
                        media.append(
                            telegram.InputMediaVideo(media=msg.file_id,
                                                     caption=txt))

                    msg.sent = True
                    msg.ch_a = True
                    new_message.append(msg)

                self.updater.bot.send_media_group(chat_id=chat_id,
                                                  media=media,
                                                  timeout=time_out)
                for msg in new_message:
                    db.update(msg)
                logging.info('media_group sent {}'.format(message.__str__()))

            # regular
            elif not message.ch_a:
                txt = editor.id_remove(text=message.txt, channel=channel)
                parse_mode = 'HTML' if message.other == 'url' else None

                if message.kind == 'photo':
                    dir_ = "image/{}.jpg".format(channel.name)
                    out = "image/{}_out.jpg".format(channel.name)
                    if channel.plan >= 1:
                        try:
                            self.updater.bot.getFile(
                                message.file_id).download(dir_)
                            txt = editor.image_watermark(photo=dir_,
                                                         out=out,
                                                         caption=message.txt,
                                                         channel=channel)
                            self.updater.bot.send_photo(
                                chat_id=message.to_channel,
                                photo=open(out, 'rb'),
                                caption=txt,
                                timeout=time_out)
                        except Exception:
                            txt = editor.id_remove(text=message.txt,
                                                   channel=channel)
                            self.updater.bot.send_photo(
                                chat_id=message.to_channel,
                                photo=message.file_id,
                                caption=txt)
                    else:
                        txt = editor.id_remove(message.txt, channel)
                        self.updater.bot.send_photo(chat_id=message.to_channel,
                                                    photo=message.file_id,
                                                    caption=txt)

                elif message.kind == 'video':
                    form = message.mime
                    dir_ = "vid/{}.{}".format(channel.name, form)
                    out = "vid/{}_out.mp4".format(channel.name)

                    if message.size <= limit_size and channel.plan >= 3:
                        self.updater.bot.getFile(message.file_id).download(
                            dir_, timeout=20)
                        try:
                            txt = editor.vid_watermark(vid=dir_,
                                                       out=out,
                                                       kind=message.kind,
                                                       caption=message.txt,
                                                       channel=channel)

                            self.updater.bot.send_video(
                                chat_id=message.to_channel,
                                video=open(out, 'rb'),
                                caption=txt,
                                timeout=time_out)
                        except Exception:
                            self.updater.bot.send_video(
                                chat_id=message.to_channel,
                                video=message.file_id,
                                caption=txt)
                    else:
                        txt = editor.id_remove(text=message.txt,
                                               channel=channel)
                        self.updater.bot.send_video(chat_id=message.to_channel,
                                                    video=message.file_id,
                                                    caption=txt)

                elif message.kind == 'animation':
                    form = message.mime
                    dir_ = "gif/{}.{}".format(channel.name, form)
                    out = "gif/{}_out.mp4".format(channel.name)

                    if message.size <= limit_size and channel.plan >= 2:
                        try:
                            self.updater.bot.getFile(message.file_id).download(
                                dir_, timeout=20)
                            txt = editor.vid_watermark(vid=dir_,
                                                       out=out,
                                                       kind=message.kind,
                                                       caption=message.txt,
                                                       channel=channel)

                            self.updater.bot.send_animation(
                                chat_id=message.to_channel,
                                animation=open(out, 'rb'),
                                caption=txt,
                                timeout=time_out)
                        except Exception as _:
                            self.updater.bot.send_animation(
                                chat_id=message.to_channel,
                                animation=message.file_id,
                                caption=txt)
                    else:
                        txt = editor.id_remove(text=message.txt,
                                               channel=channel)
                        self.updater.bot.send_animation(
                            chat_id=message.to_channel,
                            animation=message.file_id,
                            caption=txt)

                elif message.kind == 'text':
                    self.updater.bot.send_message(chat_id=message.to_channel,
                                                  text=txt,
                                                  parse_mode=parse_mode)

                elif message.kind == 'audio':
                    self.updater.bot.send_audio(chat_id=message.to_channel,
                                                audio=message.file_id,
                                                caption=txt)

                elif message.kind == 'document':
                    self.updater.bot.send_document(chat_id=message.to_channel,
                                                   document=message.file_id,
                                                   caption=txt)

                elif message.kind == 'v_note':
                    self.updater.bot.send_video_note(
                        chat_id=message.to_channel, video_note=message.file_id)

                elif message.kind == 'voice':
                    self.updater.bot.send_voice(chat_id=message.to_channel,
                                                voice=message.file_id,
                                                caption=txt)

                elif message.kind == 'sticker':
                    self.updater.bot.send_sticker(chat_id=message.to_channel,
                                                  sticker=message.file_id,
                                                  caption=txt)

                try:
                    if dir_ or out:
                        _ = [os.remove(i) for i in [dir_, out]]
                except Exception:
                    pass

                logging.debug('send_to_ch {}'.format(message.__str__()))
                message.sent = True
                message.ch_a = True
                db.update(message)

        except IndexError:
            pass
        except AttributeError:
            pass
        except Exception as E:
            if isinstance(message, db.Message):
                message.sent = True
                message.ch_a = True
                db.update(message)
                logging.error('send_to_ch attempt {} Error: {}'.format(
                    message.__str__(), E))
            else:
                logging.error(
                    'send_to_ch attempt {} Error: not a message'.format(
                        message.__str__()))