예제 #1
0
def getCategory(current_category_key):
    current_category = None
    lineage = []
    
    try:
        current_category = Category.get(db.Key(current_category_key))
        lineage = [Category.get(key) for key in current_category.lineage]
    except db.BadKeyError:
        pass
    except AttributeError:
        pass
    
    #todo - massive oppurtunity for optimization
    retval = current_category.key().__str__() + ',' + current_category.name + ';'
    
    for category in lineage:
        retval += category.key().__str__() + ',' + category.name + ','
    retval += ';'
    
    for category in Category.children(current_category):
        retval += category.key().__str__() + ',' + category.name + ','
    
    print 'Content-Type: text/plain;charset=UTF-8'
    print ''
    print retval
예제 #2
0
 def post(self, cid):
     
     try:
         category = Category.get(id = cid)
     except:
         self.flash("此分类不存在")
         self.redirect("/admin/categorys")
         return
     
     name = self.get_argument("name", None)
     slug = self.get_argument("slug", None)
     order = int(self.get_argument("order", 1))
     
     category.name = name
     category.slug = slug
     category.order = order
     
     try:
         category.validate()
         category.save()
         self.flash(u"分类%s修改成功" % name)
         self.redirect("/admin/categorys")
         return
     except Exception, ex:
         self.flash(str(ex))
예제 #3
0
    def post(self, cid):

        try:
            category = Category.get(id=cid)
        except:
            self.flash("此分类不存在")
            self.redirect("/admin/categorys")
            return

        name = self.get_argument("name", None)
        slug = self.get_argument("slug", None)
        order = int(self.get_argument("order", 1))

        category.name = name
        category.slug = slug
        category.order = order

        try:
            category.validate()
            category.save()
            self.flash(u"分类%s修改成功" % name)
            self.redirect("/admin/categorys")
            return
        except Exception, ex:
            self.flash(str(ex))
예제 #4
0
    def post(self, caid):
        try:
            categoryattr = CategoryAttr.get(id=caid)
            category = Category.get(id=categoryattr.cid)
        except:
            self.flash("此分类属性不存在")
            self.redirect("/admin/categorys")
            return

        name = self.get_argument("name", None)
        dec = self.get_argument("dec", "")
        order = int(self.get_argument("order", 1))

        categoryattr.name = name
        categoryattr.dec = dec
        categoryattr.order = order

        try:
            categoryattr.validate()
            categoryattr.save()
            self.flash(u"分类属性%s修改成功" % name)
            self.redirect("/admin/categoryattrs/%d" % int(categoryattr.cid))
            return
        except Exception, ex:
            self.flash(str(ex))
예제 #5
0
    def get(self, sid):
        try:
            shop = Shop.get(id=sid)
        except:
            self.flash("此商品不存在")
            self.redirect("/admin/addshop")
            return

        try:
            category = Category.get(id=shop.cid)
        except:
            pass

        categoryattrs = CategoryAttr.select().where(
            CategoryAttr.cid == shop.cid)

        pics = [
            shoppic.path
            for shoppic in ShopPic.select().where(ShopPic.sid == sid)
        ]
        shop.args = simplejson.loads(shop.args)

        self.render('admin/editshop.html',
                    shop=shop,
                    pics=pics,
                    category=category,
                    categoryattrs=categoryattrs)
예제 #6
0
파일: admin.py 프로젝트: gislite/cakeshop
 def post(self, cid):
     try:
         category = Category.get(id = cid)
     except:
         self.flash("此分类不存在")
         self.redirect("/admin/categorys")
         return
     
     name = self.get_argument("name", None)
     dec = self.get_argument("dec", "")
     order = int(self.get_argument("order", 1))
         
     categoryattr = CategoryAttr()
     categoryattr.cid = cid
     categoryattr.name = name
     categoryattr.dec = dec
     categoryattr.order = order
     
     try:
         categoryattr.validate()
         categoryattr.save()
         self.flash("分类属性%s添加成功" % name)
         self.redirect("/admin/categoryattrs/%d" % int(cid))
         return
     except Exception as ex:
         self.flash(str(ex))
     
     self.render('admin/addcategoryattr.html', category = category, maxorder = CategoryAttr.maxorder(cid))
예제 #7
0
 def post(self, caid):
     try:
         categoryattr = CategoryAttr.get(id = caid)
         category = Category.get(id = categoryattr.cid)
     except:
         self.flash("此分类属性不存在")
         self.redirect("/admin/categorys")
         return
     
     name = self.get_argument("name", None)
     dec = self.get_argument("dec", "")
     order = int(self.get_argument("order", 1))
         
     categoryattr.name = name
     categoryattr.dec = dec
     categoryattr.order = order
     
     try:
         categoryattr.validate()
         categoryattr.save()
         self.flash(u"分类属性%s修改成功" % name)
         self.redirect("/admin/categoryattrs/%d" % int(categoryattr.cid))
         return
     except Exception, ex:
         self.flash(str(ex))
예제 #8
0
    def get(self, ename):

        try:
            shop = Shop.get(ename=ename)
            shop.views = shop.views + 1
            shop.save()
            category = Category.get(id=shop.cid)
        except:
            raise HTTPError(404)
            return

        categoryattrs = CategoryAttr.select().where(
            CategoryAttr.cid == shop.cid)
        shopattrs = ShopAttr.select().where(ShopAttr.sid == shop.id)
        if shop.args:
            shop.args = simplejson.loads(shop.args)
        pics = ShopPic.select().where(ShopPic.sid == shop.id)

        recomshops = Shop.select().where((Shop.status == 1)
                                         & (Shop.id != shop.id)).paginate(
                                             1, 5)
        self.render("shop/shop.html",
                    shop=shop,
                    category=category,
                    categoryattrs=categoryattrs,
                    shopattrs=shopattrs,
                    pics=pics,
                    recomshops=recomshops)
예제 #9
0
    def apply(self):
        try:
            if self.subject is None:
                self.delete_instance()
                return False
        except Bot.DoesNotExist:
            self.delete_instance()
            return False

        if self.action == 'category':
            from model import Category
            try:
                cat = Category.get(Category.id == self.value)
                self.subject.category = cat
            except Category.DoesNotExist:
                raise AttributeError("Category to change to does not exist.")
        elif self.action == 'name':
            self.subject.name = self.value
        elif self.action == 'username':
            self.subject.username = self.value
        elif self.action == 'description':
            self.subject.description = self.value
        elif self.action == 'extra':
            self.subject.extra = self.value
        elif self.action == 'country':
            if self._value == 'None' or self._value is None:
                self.subject.country = None
            else:
                from model import Country
                try:
                    con = Country.get(id=self._value)
                    self.subject.country = con
                except Country.DoesNotExist:
                    raise AttributeError(
                        "Country to change to does not exist.")
        elif self.action == 'inlinequeries':
            self.subject.inlinequeries = bool(self.value)
        elif self.action == 'official':
            self.subject.official = bool(self.value)
        elif self.action == 'offline':
            self.subject.offline = bool(self.value)
        elif self.action == 'spam':
            self.subject.spam = bool(self.value)
        elif self.action == 'add_keyword':
            kw_obj = Keyword(name=self.value, entity=self.subject)
            kw_obj.save()
        elif self.action == 'remove_keyword':
            try:
                kw_obj = Keyword.get(name=self.value, entity=self.subject)
                kw_obj.delete_instance()
            except Keyword.DoesNotExist:
                raise AttributeError(
                    "Keyword to delete does not exist anymore.")

        self.subject.save()

        self.executed = True
        self.save()
        return True
예제 #10
0
파일: admin.py 프로젝트: lyzhanghai/wxshop
 def get(self, cid):
     try:
         category = Category.get(id = cid)
     except:
         self.flash("此分类不存在")
         self.redirect("/admin/categorys")
         return
     
     self.render('admin/addcategoryattr.html', category = category, maxorder = CategoryAttr.maxorder(cid))
예제 #11
0
파일: admin.py 프로젝트: lyzhanghai/wxshop
 def get(self, cid):
     try:
         category = Category.get(id = cid)
     except:
         self.flash("此分类不存在")
         self.redirect("/admin/addshop")
         return
     
     categoryattrs = CategoryAttr.select().where(CategoryAttr.cid == cid)
     self.render('admin/addcshop.html', category = category, categoryattrs = categoryattrs)
예제 #12
0
파일: admin.py 프로젝트: lyzhanghai/wxshop
 def get(self, cid):
     try:
         category = Category.get(id = cid)
     except:
         self.flash("此分类不存在")
         self.redirect("/admin/categorys")
         return
     
     categoryattrs = [categoryattr for categoryattr in CategoryAttr.select().where(CategoryAttr.cid == cid)]
     self.render('admin/categoryattr.html', category = category, categoryattrs = categoryattrs)
예제 #13
0
    def get(self):
        current_category_key = self.request.get("category")
        current_category = None
        lineage = []

        try:
            current_category = Category.get(db.Key(current_category_key))
            lineage = [Category.get(key) for key in current_category.lineage]
        except db.BadKeyError:
            pass
        except AttributeError:
            pass

        child_categories = Category.children(current_category)
        self.tpl_vars["current_category"] = current_category
        self.tpl_vars["child_categories"] = child_categories
        self.tpl_vars["lineage"] = lineage
        path = os.path.join(os.path.dirname(__file__), "templates/admin/index.html")
        self.response.out.write(template.render(path, self.tpl_vars))
예제 #14
0
파일: admin.py 프로젝트: lyzhanghai/wxshop
 def get(self, caid):
     try:
         categoryattr = CategoryAttr.get(id = caid)
         category = Category.get(id = categoryattr.cid)
     except:
         self.flash("此分类属性不存在")
         self.redirect("/admin/categorys")
         return
     
     self.render('admin/editcategoryattr.html', category = category, categoryattr = categoryattr)
예제 #15
0
    def get(self, cid):
        cid = int(cid)

        try:
            category = Category.get(id=cid)
        except:
            self.flash("此分类不存在")
            self.redirect("/admin/categorys")
            return

        self.render('admin/editcategory.html', category=category)
예제 #16
0
 def get(self, cid):
     cid = int(cid)
     
     try:
         category = Category.get(id = cid)
     except:
         self.flash("此分类不存在")
         self.redirect("/admin/categorys")
         return
     
     self.render('admin/editcategory.html', category = category)
예제 #17
0
    def post(self):
        parent_key = self.request.get("parent_key")
        name = self.request.get("category_name")

        if len(name) < 3:
            pass  # no feedback, as of now
        else:
            try:
                parent = Category.get(db.Key(parent_key))
                Category.new(name, parent)
            except db.BadKeyError:
                pass  # no feedback, as of now
            except:
                pass  # no feedback, as of now

        self.redirect("./?category=" + parent_key)
예제 #18
0
    def _md_plaintext(self):
        uname = util.escape_markdown(self.subject.username)
        value = self.value

        text = ''
        if self.action == 'category':
            from model import Category
            try:
                cat = Category.get(id=self.value)
                text += "move {} ➜ {}".format(uname, cat.name)
            except Category.DoesNotExist:
                raise AttributeError("Category to change to does not exist.")
        elif self.action == 'name':
            text += "set name {} ➜ {}".format(uname, str(value))
        elif self.action == 'username':
            text += "set username {} ➜ {}".format(uname, str(value))
        elif self.action == 'description':
            text += "change description text of {}".format(uname)
        elif self.action == 'extra':
            text += "change extra text {}".format(uname)
        elif self.action == 'country':
            text += "change country {} ➜ ".format(uname)
            if self._value == 'None' or self._value is None:
                text += "None"
            else:
                from model import Country
                try:
                    con = Country.get(id=self._value)
                    text += str(con)
                except Country.DoesNotExist:
                    raise AttributeError(
                        "Country to change to does not exist.")
        elif self.action == 'inlinequeries':
            text += "toggle inlinequeries {} ➜ {}".format(uname, str(value))
        elif self.action == 'official':
            text += "toggle official {} ➜ {}".format(uname, str(value))
        elif self.action == 'offline':
            text += "set {} {}".format('💤' if bool(value) else 'online',
                                       uname)
        elif self.action == 'spam':
            text += "mark {} as spammy".format(uname)
        elif self.action == 'add_keyword':
            text += "add keyword #{} to {}".format(str(value), uname)
        elif self.action == 'remove_keyword':
            text += "remove keyword #{} from {}".format(str(value), uname)
        return text
예제 #19
0
    def get(self, slug):
        ccategory = None
        if slug:
            try:
                ccategory = Category.get(slug=slug)
            except:
                self.redirect("/list/")
                return

        keyword = self.get_argument("keyword", None)

        page = int(self.get_argument("page", 1))
        order = self.get_argument("order", None)

        pagesize = self.settings['admin_pagesize']

        categorys = self.get_categorys()

        sq = Shop.select(Shop.name, Shop.ename, Shop.cover, Shop.price)
        total = sq.count()

        if ccategory:
            sq = sq.where((Shop.cid == ccategory.id) & (Shop.status != 9))
        elif keyword:
            keyword = "%" + keyword + "%"
            sq = sq.where((Shop.name % keyword) & (Shop.status != 9))
        else:
            sq = sq.where((Shop.cid != 2) & (Shop.status != 9))

        if order:
            sq = sq.order_by(Shop.orders.desc())
        else:
            sq = sq.order_by(Shop.views.desc())

        shops = []
        for shop in sq.paginate(page, pagesize):
            shop.price = shop.price.split("~")[0]
            shops.append(shop)

        self.render("shop/list.html",
                    ccategory=ccategory,
                    categorys=categorys,
                    shops=shops,
                    total=total,
                    page=page,
                    pagesize=pagesize)
예제 #20
0
    def value(self):
        # cast types
        from model import Category
        from model import Country

        if self._value == 'None':
            return None

        if self.action in self.BOOLEAN_ACTIONS:
            return bool(self._value)
        elif self.action == 'category':
            return Category.get(id=self._value)
        elif self.action == 'country':
            if self._value is None:
                return None
            return Country.get(id=self._value)
        else:
            return str(self._value) if self._value else None
예제 #21
0
 def get(self, sid):
     try:
         shop = Shop.get(id = sid)
     except:
         self.flash("此商品不存在")
         self.redirect("/admin/addshop")
         return
     
     try:
         category = Category.get(id = shop.cid)
     except:
         pass
     
     categoryattrs = CategoryAttr.select().where(CategoryAttr.cid == shop.cid)
     
     pics = [shoppic.path for shoppic in ShopPic.select().where(ShopPic.sid == sid)]
     shop.args = simplejson.loads(shop.args)
     
     self.render('admin/editshop.html', shop = shop, pics = pics, category = category, categoryattrs = categoryattrs)
예제 #22
0
 def get(self, ename):
     
     try:
         shop = Shop.get(ename = ename)
         shop.views = shop.views + 1
         shop.save()
         category = Category.get(id = shop.cid)
     except:
         raise HTTPError(404)
         return
     
     categoryattrs = CategoryAttr.select().where(CategoryAttr.cid == shop.cid)
     shopattrs = ShopAttr.select().where(ShopAttr.sid == shop.id)
     if shop.args:
         shop.args = simplejson.loads(shop.args)
     pics = ShopPic.select().where(ShopPic.sid == shop.id)
     
     recomshops = Shop.select().where((Shop.status == 1) & (Shop.id != shop.id)).paginate(1, 5)
     self.render("shop/shop.html", shop = shop, category = category, categoryattrs = categoryattrs, shopattrs = shopattrs, pics = pics, recomshops = recomshops)
예제 #23
0
파일: basic.py 프로젝트: n8wachT/BotListBot
def start(bot, update, chat_data, args):
    tg_user = update.message.from_user
    chat_id = tg_user.id

    # Get or create the user from/in database
    User.from_telegram_object(tg_user)

    if isinstance(args, list) and len(args) > 0:
        # CATEGORY BY ID
        try:
            cat = Category.get(Category.id == args[0])
            from components.explore import send_category
            return send_category(bot, update, chat_data, cat)
        except (ValueError, Category.DoesNotExist):
            pass

        query = ' '.join(args).lower()

        # SPECIFIC DEEP-LINKED QUERIES
        if query == const.DeepLinkingActions.CONTRIBUTING:
            return help.contributing(bot, update, quote=False)
        elif query == const.DeepLinkingActions.EXAMPLES:
            return help.examples(bot, update, quote=False)
        elif query == const.DeepLinkingActions.RULES:
            return help.rules(bot, update, quote=False)
        elif query == const.DeepLinkingActions.SEARCH:
            return search_handler(bot, update, chat_data)

        # SEARCH QUERY
        search_query(bot, update, chat_data, query)

    else:
        bot.sendSticker(
            chat_id,
            open(
                os.path.join(appglobals.ROOT_DIR, 'assets', 'sticker',
                             'greetings-humanoids.webp'), 'rb'))
        help.help(bot, update)
        util.wait(bot, update)
        if util.is_private_message(update):
            main_menu(bot, update)
        return ConversationHandler.END
예제 #24
0
 def get(self, slug):
     ccategory= None
     if slug:
         try:
             ccategory = Category.get(slug = slug)
         except:
             self.redirect("/list/")
             return
     
     keyword = self.get_argument("keyword", None)
     
     page = int(self.get_argument("page", 1))
     order = self.get_argument("order", None)
     
     pagesize = self.settings['admin_pagesize']
     
     categorys = self.get_categorys()
     
     sq = Shop.select(Shop.name, Shop.ename, Shop.cover, Shop.price)
     total = sq.count()
     
     if ccategory:
         sq = sq.where((Shop.cid == ccategory.id) & (Shop.status != 9))
     elif keyword:
         keyword = "%" + keyword + "%"
         sq = sq.where((Shop.name % keyword) & (Shop.status != 9))
     else:
         sq = sq.where((Shop.cid != 2) & (Shop.status != 9))
     
     if order:
         sq = sq.order_by(Shop.orders.desc())
     else:
         sq = sq.order_by(Shop.views.desc())
     
     shops = []
     for shop in sq.paginate(page, pagesize):
         shop.price = shop.price.split("~")[0]
         shops.append(shop)
     
     self.render("shop/list.html", ccategory = ccategory, categorys = categorys, shops = shops, total = total, page = page, pagesize = pagesize)
예제 #25
0
def callback_router(bot, update, chat_data, user_data, job_queue):
    obj = json.loads(str(update.callback_query.data))
    user = User.from_update(update)

    try:
        if 'a' in obj:
            action = obj['a']

            # BOTLISTCHAT
            if action == CallbackActions.DELETE_CONVERSATION:
                botlistchat.delete_conversation(bot, update, chat_data)
            # HELP
            elif action == CallbackActions.HELP:
                help.help(bot, update)
            elif action == CallbackActions.CONTRIBUTING:
                help.contributing(bot, update)
            elif action == CallbackActions.EXAMPLES:
                help.examples(bot, update)
            # BASIC QUERYING
            elif action == CallbackActions.SELECT_CATEGORY:
                select_category(bot, update, chat_data)
            elif action == CallbackActions.SELECT_BOT_FROM_CATEGORY:
                category = Category.get(id=obj['id'])
                send_category(bot, update, chat_data, category)
            elif action == CallbackActions.SEND_BOT_DETAILS:
                item = Bot.get(id=obj['id'])
                send_bot_details(bot, update, chat_data, item)
            # FAVORITES
            elif action == CallbackActions.TOGGLE_FAVORITES_LAYOUT:
                value = obj['v']
                favorites.toggle_favorites_layout(bot, update, value)
            elif action == CallbackActions.ADD_FAVORITE:
                favorites.add_favorite_handler(bot, update)
            elif action == CallbackActions.REMOVE_FAVORITE_MENU:
                favorites.remove_favorite_menu(bot, update)
            elif action == CallbackActions.REMOVE_FAVORITE:
                to_remove = Favorite.get(id=obj['id'])
                bot_details = to_remove.bot
                to_remove.delete_instance()
                if obj.get('details'):
                    send_bot_details(bot, update, chat_data, bot_details)
                else:
                    favorites.remove_favorite_menu(bot, update)
            elif action == CallbackActions.SEND_FAVORITES_LIST:
                favorites.send_favorites_list(bot, update)
            elif action == CallbackActions.ADD_ANYWAY:
                favorites.add_custom(bot, update, obj['u'])
            elif action == CallbackActions.ADD_TO_FAVORITES:
                details = obj.get('details')
                discreet = obj.get('discreet', False) or details
                item = Bot.get(id=obj['id'])
                favorites.add_favorite(bot,
                                       update,
                                       item,
                                       callback_alert=discreet)
                if details:
                    send_bot_details(bot, update, chat_data, item)
            # ACCEPT/REJECT BOT SUBMISSIONS
            elif action == CallbackActions.APPROVE_REJECT_BOTS:
                custom_approve_list = [Bot.get(id=obj['id'])]
                admin.approve_bots(bot,
                                   update,
                                   override_list=custom_approve_list)
            elif action == CallbackActions.ACCEPT_BOT:
                to_accept = Bot.get(id=obj['id'])
                admin.edit_bot_category(bot, update, to_accept,
                                        CallbackActions.BOT_ACCEPTED)
                # Run in x minutes, giving the moderator enough time to edit bot details
                job_queue.run_once(
                    lambda b, job: botlistchat.
                    notify_group_submission_accepted(b, job, to_accept),
                    settings.BOT_ACCEPTED_IDLE_TIME * 60)
            elif action == CallbackActions.RECOMMEND_MODERATOR:
                bot_in_question = Bot.get(id=obj['id'])
                admin.recommend_moderator(bot, update, bot_in_question,
                                          obj['page'])
            elif action == CallbackActions.SELECT_MODERATOR:
                bot_in_question = Bot.get(id=obj['bot_id'])
                moderator = User.get(id=obj['uid'])
                admin.share_with_moderator(bot, update, bot_in_question,
                                           moderator)
                admin.approve_bots(bot, update, obj['page'])
            elif action == CallbackActions.REJECT_BOT:
                to_reject = Bot.get(id=obj['id'])
                notification = obj.get('ntfc', True)
                admin.reject_bot_submission(bot,
                                            update,
                                            to_reject,
                                            verbose=False,
                                            notify_submittant=notification)
                admin.approve_bots(bot, update, obj['page'])
            elif action == CallbackActions.BOT_ACCEPTED:
                to_accept = Bot.get(id=obj['bid'])
                category = Category.get(id=obj['cid'])
                admin.accept_bot_submission(bot, update, to_accept, category)
            elif action == CallbackActions.COUNT_THANK_YOU:
                new_count = obj.get('count', 1)
                basic.count_thank_you(bot, update, new_count)
            # ADD BOT
            # elif action == CallbackActions.ADD_BOT_SELECT_CAT:
            #     category = Category.get(id=obj['id'])
            #     admin.add_bot(bot, update, chat_data, category)
            # EDIT BOT
            elif action == CallbackActions.EDIT_BOT:
                to_edit = Bot.get(id=obj['id'])
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_SELECT_CAT:
                to_edit = Bot.get(id=obj['id'])
                admin.edit_bot_category(bot, update, to_edit)
            elif action == CallbackActions.EDIT_BOT_CAT_SELECTED:
                to_edit = Bot.get(id=obj['bid'])
                cat = Category.get(id=obj['cid'])
                botproperties.change_category(bot, update, to_edit, cat)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_COUNTRY:
                to_edit = Bot.get(id=obj['id'])
                botproperties.set_country_menu(bot, update, to_edit)
            elif action == CallbackActions.SET_COUNTRY:
                to_edit = Bot.get(id=obj['bid'])
                if obj['cid'] == 'None':
                    country = None
                else:
                    country = Country.get(id=obj['cid'])
                botproperties.set_country(bot, update, to_edit, country)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_DESCRIPTION:
                to_edit = Bot.get(id=obj['id'])
                botproperties.set_text_property(bot, update, chat_data,
                                                'description', to_edit)
            elif action == CallbackActions.EDIT_BOT_EXTRA:
                to_edit = Bot.get(id=obj['id'])
                botproperties.set_text_property(bot, update, chat_data,
                                                'extra', to_edit)
            elif action == CallbackActions.EDIT_BOT_NAME:
                to_edit = Bot.get(id=obj['id'])
                botproperties.set_text_property(bot, update, chat_data, 'name',
                                                to_edit)
            elif action == CallbackActions.EDIT_BOT_USERNAME:
                to_edit = Bot.get(id=obj['id'])
                botproperties.set_text_property(bot, update, chat_data,
                                                'username', to_edit)
            # elif action == CallbackActions.EDIT_BOT_KEYWORDS:
            #     to_edit = Bot.get(id=obj['id'])
            #     botproperties.set_keywords_init(bot, update, chat_data, to_edit)
            elif action == CallbackActions.APPLY_ALL_CHANGES:
                to_edit = Bot.get(id=obj['id'])
                admin.apply_all_changes(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_INLINEQUERIES:
                to_edit = Bot.get(id=obj['id'])
                value = bool(obj['value'])
                botproperties.toggle_value(bot, update, 'inlinequeries',
                                           to_edit, value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_OFFICIAL:
                to_edit = Bot.get(id=obj['id'])
                value = bool(obj['value'])
                botproperties.toggle_value(bot, update, 'official', to_edit,
                                           value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_OFFLINE:
                to_edit = Bot.get(id=obj['id'])
                value = bool(obj['value'])
                botproperties.toggle_value(bot, update, 'offline', to_edit,
                                           value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_SPAM:
                to_edit = Bot.get(id=obj['id'])
                value = bool(obj['value'])
                botproperties.toggle_value(bot, update, 'spam', to_edit, value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.CONFIRM_DELETE_BOT:
                to_delete = Bot.get(id=obj['id'])
                botproperties.delete_bot_confirm(bot, update, to_delete)
            elif action == CallbackActions.DELETE_BOT:
                to_edit = Bot.get(id=obj['id'])
                botproperties.delete_bot(bot, update, to_edit)
                send_category(bot, update, to_edit.category)
            elif action == CallbackActions.ACCEPT_SUGGESTION:
                suggestion = Suggestion.get(id=obj['id'])
                components.botproperties.accept_suggestion(
                    bot, update, suggestion)
                admin.approve_suggestions(bot, update, page=obj['page'])
            elif action == CallbackActions.REJECT_SUGGESTION:
                suggestion = Suggestion.get(id=obj['id'])
                suggestion.delete_instance()
                admin.approve_suggestions(bot, update, page=obj['page'])
            elif action == CallbackActions.CHANGE_SUGGESTION:
                suggestion = Suggestion.get(id=obj['id'])
                botproperties.change_suggestion(bot,
                                                update,
                                                suggestion,
                                                page_handover=obj['page'])
            elif action == CallbackActions.SWITCH_SUGGESTIONS_PAGE:
                page = obj['page']
                admin.approve_suggestions(bot, update, page)
            elif action == CallbackActions.SWITCH_APPROVALS_PAGE:
                admin.approve_bots(bot, update, page=obj['page'])
            elif action == CallbackActions.SET_NOTIFICATIONS:
                set_notifications(bot, update, obj['value'])
            elif action == CallbackActions.NEW_BOTS_SELECTED:
                show_new_bots(bot, update, chat_data, back_button=True)
            elif action == CallbackActions.ABORT_SETTING_KEYWORDS:
                to_edit = Bot.get(id=obj['id'])
                admin.edit_bot(bot, update, chat_data, to_edit)
            # SENDING BOTLIST
            elif action == CallbackActions.SEND_BOTLIST:
                silent = obj.get('silent', False)
                re_send = obj.get('re', False)
                botlist.send_botlist(bot,
                                     update,
                                     resend=re_send,
                                     silent=silent)
            elif action == CallbackActions.RESEND_BOTLIST:
                botlist.send_botlist(bot, update, resend=True)
            # BROADCASTING
            elif action == 'send_broadcast':
                broadcasts.send_broadcast(bot, update, user_data)
            elif action == 'pin_message':
                broadcasts.pin_message(bot, update, obj['mid'])
            elif action == 'add_thank_you':
                basic.add_thank_you_button(bot, update, obj['cid'], obj['mid'])
            # EXPLORING
            elif action == CallbackActions.EXPLORE_NEXT:
                explore.explore(bot, update, chat_data)
    except Exception as e:
        traceback.print_exc()

        # get the callback action in plaintext
        actions = dict(CallbackActions.__dict__)
        a = next(k for k, v in actions.items() if v == obj.get('a'))
        util.send_md_message(
            bot, settings.ADMINS[0],
            "Exception in callback query for {}:\n{}\n\nWith CallbackAction {}\n\nWith data:\n{}"
            .format(user.markdown_short, util.escape_markdown(e),
                    util.escape_markdown(a), util.escape_markdown(str(obj))))
    finally:
        bot.answerCallbackQuery(update.callback_query.id)
        return ConversationHandler.END
예제 #26
0
 def post(self, sid):
     try:
         shop = Shop.get(id = sid)
     except:
         self.flash("此商品不存在")
         self.redirect("/admin/addshop")
         return
     
     try:
         category = Category.get(id = shop.cid)
     except:
         pass
     
     categoryattrs = CategoryAttr.select().where(CategoryAttr.cid == shop.cid)
     
     opics = [shoppic.path for shoppic in ShopPic.select().where(ShopPic.sid == sid)]
     
     cover = self.get_argument("cover", None)
     pics = self.get_argument("pics", None)
     name = self.get_argument("name", None)
     ename = self.get_argument("ename", None)
     price = self.get_argument("price", 0.0)
     views = int(self.get_argument("views", 0))
     
     if category.id == 2:
         price = str(float(price))
     
     level = int(self.get_argument("level", 3))
     resume = self.get_argument("resume", "")
     intro = self.get_argument("intro", "")
     prompt = self.get_argument("prompt", "")
     
     try:
         shop.name = name
         shop.ename = ename
         shop.level = level
         shop.resume = resume
         shop.intro = intro
         shop.prompt = prompt
         shop.price = price
         shop.views = views
         
         args = {}
         for categoryattr in categoryattrs:
             caid = str(categoryattr.id)
             args['attr_' + caid] = self.get_argument('attr_' + caid, '')
         
         shop.args = simplejson.dumps(args)
         
         if pics:
             pics = pics.split(',')
             pics = [pic.replace('/upload/', '') for pic in pics]
             if not cover:
                 cover = pics[0]
         
         if not cover:
             cover = ''
         
         shop.cover = cover.replace('/upload/', '')
         shop.validate()
         shop.save()
         
         if isinstance(pics, list):
             for pic in pics:
                 if pic not in opics:
                     shoppic = ShopPic()
                     shoppic.sid = shop.id
                     shoppic.path = pic
                     shoppic.save()
             
             for pic in opics:
                 if pic not in pics:
                     ShopPic.delete().where(ShopPic.path == pic).execute()
         
         self.flash(u"修改商品%s成功" % name, 'ok')
         self.redirect("/admin/shops")
         return
     except Exception, ex:
         shop.args = simplejson.loads(shop.args)
         self.flash(str(ex))
예제 #27
0
def new_channel_post(bot, update, photo=None):
    post = update.channel_post
    if post.chat.username != settings.SELF_CHANNEL_USERNAME:
        return
    text = post.text

    channel, created = Channel.get_or_create(chat_id=post.chat_id,
                                             username=post.chat.username)
    if created:
        channel.save()

    category_list = '•Share your bots to the @BotListChat using the hashtag #new' in text
    intro = 'Hi! Welcome' in text
    category = text[0] == '•' and not category_list
    new_bots_list = 'NEW→' in text

    # TODO: is this a document?
    if photo:
        pass
    elif category:
        try:
            # get the category meta data
            meta = re.match(r'•(.*?)([A-Z].*):(?:\n(.*):)?', text).groups()
            if len(meta) < 2:
                raise ValueError("Category could not get parsed.")

            emojis = str.strip(meta[0])
            name = str.strip(meta[1])
            extra = str.strip(meta[2]) if meta[2] else None
            try:
                cat = Category.get(name=name)
            except Category.DoesNotExist:
                cat = Category(name=name)
            cat.emojis = emojis
            cat.extra = extra
            cat.save()

            # get the bots in that category
            bots = re.findall(r'^(🆕)?.*(@\w+)( .+)?$', text, re.MULTILINE)
            languages = Country.select().execute()
            for b in bots:
                username = b[1]
                try:
                    new_bot = Bot.by_username(username)
                except Bot.DoesNotExist:
                    new_bot = Bot(username=username)

                new_bot.category = cat

                new_bot.inlinequeries = "🔎" in b[2]
                new_bot.official = "🔹" in b[2]

                extra = re.findall(r'(\[.*\])', b[2])
                if extra:
                    new_bot.extra = extra[0]

                # find language
                for lang in languages:
                    if lang.emoji in b[2]:
                        new_bot.country = lang

                if b[0]:
                    new_bot.date_added = datetime.date.today()
                else:
                    new_bot.date_added = datetime.date.today(
                    ) - datetime.timedelta(days=31)

                new_bot.save()
        except AttributeError:
            log.error("Error parsing the following text:\n" + text)
예제 #28
0
    def post(self, sid):
        try:
            shop = Shop.get(id=sid)
        except:
            self.flash("此商品不存在")
            self.redirect("/admin/addshop")
            return

        try:
            category = Category.get(id=shop.cid)
        except:
            pass

        categoryattrs = CategoryAttr.select().where(
            CategoryAttr.cid == shop.cid)

        opics = [
            shoppic.path
            for shoppic in ShopPic.select().where(ShopPic.sid == sid)
        ]

        cover = self.get_argument("cover", None)
        pics = self.get_argument("pics", None)
        name = self.get_argument("name", None)
        ename = self.get_argument("ename", None)
        price = self.get_argument("price", 0.0)
        views = int(self.get_argument("views", 0))

        if category.id == 2:
            price = str(float(price))

        level = int(self.get_argument("level", 3))
        resume = self.get_argument("resume", "")
        intro = self.get_argument("intro", "")
        prompt = self.get_argument("prompt", "")

        try:
            shop.name = name
            shop.ename = ename
            shop.level = level
            shop.resume = resume
            shop.intro = intro
            shop.prompt = prompt
            shop.price = price
            shop.views = views

            args = {}
            for categoryattr in categoryattrs:
                caid = str(categoryattr.id)
                args['attr_' + caid] = self.get_argument('attr_' + caid, '')

            shop.args = simplejson.dumps(args)

            if pics:
                pics = pics.split(',')
                pics = [pic.replace('/upload/', '') for pic in pics]
                if not cover:
                    cover = pics[0]

            if not cover:
                cover = ''

            shop.cover = cover.replace('/upload/', '')
            shop.validate()
            shop.save()

            if isinstance(pics, list):
                for pic in pics:
                    if pic not in opics:
                        shoppic = ShopPic()
                        shoppic.sid = shop.id
                        shoppic.path = pic
                        shoppic.save()

                for pic in opics:
                    if pic not in pics:
                        ShopPic.delete().where(ShopPic.path == pic).execute()

            self.flash(u"修改商品%s成功" % name, 'ok')
            self.redirect("/admin/shops")
            return
        except Exception, ex:
            shop.args = simplejson.loads(shop.args)
            self.flash(str(ex))
예제 #29
0
파일: admin.py 프로젝트: gislite/cakeshop
 def post(self, cid):
     try:
         category = Category.get(id = cid)
     except:
         self.flash("此分类不存在")
         self.redirect("/admin/addshop")
         return
     
     categoryattrs = CategoryAttr.select().where(CategoryAttr.cid == cid)
     
     cover = self.get_argument("cover", None)
     pics = self.get_argument("pics", None)
     name = self.get_argument("name", None)
     ename = self.get_argument("ename", None)
     price = str(float(str(self.get_argument("price", 0.0))))
     level = int(self.get_argument("level", 3))
     resume = self.get_argument("resume", "")
     intro = self.get_argument("intro", "")
     prompt = self.get_argument("prompt", "")
     views = int(self.get_argument("views", 0))
     
     try:
         shop = Shop()
         shop.name = name
         shop.ename = ename
         shop.cid = cid
         shop.level = level
         shop.resume = resume
         shop.intro = intro
         shop.prompt = prompt
         shop.price = price
         shop.views = views
         
         args = {}
         for categoryattr in categoryattrs:
             caid = str(categoryattr.id)
             args['attr_' + caid] = self.get_argument('attr_' + caid, '')
         
         shop.args = simplejson.dumps(args)
         
         if pics:
             pics = pics.split(',')
             pics = [pic.replace('/upload/', '') for pic in pics]
             
             if not cover:
                 cover = pics[0]
         
         if not cover:
             cover = ''
         
         shop.cover = cover.replace('/upload/', '')
         shop.validate()
         shop.save()
         
         if isinstance(pics, list):
             for pic in pics:
                 shoppic = ShopPic()
                 shoppic.sid = shop.id
                 shoppic.path = pic
                 shoppic.save()
         
         self.flash("添加商品%s成功" % name, 'ok')
         if category.id == 2:
             self.redirect("/admin/shops")
         else:
             self.redirect("/admin/addshopattr/" + str(shop.id))
         return
     except Exception as ex:
         self.flash(str(ex))
     
     self.render('admin/addcshop.html', category = category, categoryattrs = categoryattrs)