Ejemplo n.º 1
1
Archivo: add.py Proyecto: xzmyxz/Dict
 def add_term(self):
     """
     Добавление терминов в terms.db
     """
     db = Database("terms.db")
     coursers = db.get(["all_terms"])
     all_terms = {}
     for table in coursers:
         for term, definition in coursers[table]:
             all_terms[term] = definition
     ec = ""
     while ec != "--exit":
         ec = unicode(raw_input("\nТермин: "), "utf-8")
         definition = ""
         is_exit = False
         if is_exit or ec == "--exit":
             break
         if ec in all_terms:
             print "[Термин существует]: ", all_terms[ec]
         ec2 = None
         while ec2 not in ("--exit", ""):
             ec2 = raw_input("- ")
             if ec2 == "":
                 break
             if ec2 == "--exit":
                 is_exit = True
             else:
                 definition += ec2 + " / "
             definition = definition[:-3]
         db.insert("all_terms", [ec, unicode(definition, "utf-8")])
         db.commit()
     db.close_db()
Ejemplo n.º 2
0
    def change_term(self):
        """
        Позволяет изменить значение термина.
        """
        db = Database("terms.db")
        coursers = db.get(["all_terms"])
        all_terms = {}
        for table in coursers:
            for term, definition in coursers[table]:
                all_terms[term] = definition

        ec = None
        while ec != "--exit":
            ec = unicode(raw_input("Термин: "), "utf-8")
            if ec == "--exit":
                break
            elif ec == "":
                pass
            else:
                if ec in all_terms:
                    print "Значение: ", all_terms[ec], "\n"
                    new_definition = raw_input("Новое значение: ")
                    db.delete("all_terms", [ec])
                    db.insert("all_terms", [ec, unicode(new_definition, "utf-8")])
                    db.commit()
                else:
                    print "Термина не существует!\n"
        db.close_db()
Ejemplo n.º 3
0
def free_channel(db: Database, channel_id: int):
    '''Free a channel for use in another scene'''
    c = db.get()
    c.execute(
        "UPDATE channel_scenes SET created=NULL, updated=NULL, scene_name=NULL, created_by=NULL WHERE id=?",
        (channel_id, ))
    db.commit()
Ejemplo n.º 4
0
def add_new_channel(db: Database, channel_id: int, channel_name: str):
    '''Make the database aware of a new channel'''
    c = db.get()
    c.execute("INSERT INTO channels(id) VALUES(?)", (channel_id, ))
    c.execute("INSERT INTO channel_scenes(channel_name, id) VALUES(?, ?)",
              (channel_name, channel_id))
    db.commit()
Ejemplo n.º 5
0
class UpdateList:
    def __init__(self, user_name, county_name):
        self.user_name = user_name
        self.county_name = county_name
        self.db = Database()

    def add(self, root):
        try:
            cur = self.db.cursor
            cur.callproc("add_user_list", (self.user_name, self.county_name))
            self.db.commit()
            cur.close()
            showinfo(title="Success",
                     message="Added successfully!",
                     parent=root)
        except pymysql.Error:
            showwarning(title="Warning",
                        message="This record already exists.",
                        parent=root)

    def remove(self, root):
        try:
            cur = self.db.cursor
            cur.callproc("remove_user_list",
                         (self.user_name, self.county_name))
            self.db.commit()
            cur.close()
            showinfo(title="Success",
                     message="Removed successfully!",
                     parent=root)
        except pymysql.Error:
            showerror(title="Error",
                      message="Error occurs. Please try again.",
                      parent=root)
Ejemplo n.º 6
0
def reserve_channel(db: Database, channel_id: int, scene_name: str,
                    author_id: int):
    '''Reserve a channel for a scene'''
    c = db.get()
    c.execute(
        "UPDATE channel_scenes SET created=datetime('now', 'utc'), scene_name=?, updated=datetime('now', 'utc'), created_by=? WHERE id=?",
        (scene_name, author_id, channel_id))
    db.commit()
Ejemplo n.º 7
0
 def UpdateUser(self, user_id):
     # db.loans.filter_by(db.loans.book_id==2).update({'book_id':1})
     userlevel = str(self._cboUserLevel.Text).split(" ")[0]
     Database.user.filter(Database.user.user_id == user_id).update(
         {"firstname": self._txtFirstname.Text, "lastname": self._txtLastname.Text, "userlevel": userlevel}
     )
     Database.commit()
     # Database.user.filter_by(Database.user.user_id==user_id).update({'lastname':self._txtLastname,'firstname':self._txtFirstname,'userlevel': userlevel})
     self.LoadUserData()
Ejemplo n.º 8
0
 def SaveUser(self):
     #db.loans.insert(book_id=book_id, user_name=user.name)
     userlevel_ = str(self._cboUserLevel.Text).split(" ")[0]
     Database.user.insert(username=self._txtUsername.Text,
                          firstname=self._txtFirstname.Text,
                          lastname=self._txtLastname.Text,
                          userlevel=userlevel_)
     Database.commit()
     self.LoadUserData()
Ejemplo n.º 9
0
 def SaveUser(self):
     # db.loans.insert(book_id=book_id, user_name=user.name)
     userlevel_ = str(self._cboUserLevel.Text).split(" ")[0]
     Database.user.insert(
         username=self._txtUsername.Text,
         firstname=self._txtFirstname.Text,
         lastname=self._txtLastname.Text,
         userlevel=userlevel_,
     )
     Database.commit()
     self.LoadUserData()
Ejemplo n.º 10
0
 def del_term(self):
     """
     Удаление терминов их terms.db
     """
     db = Database("terms.db")
     ec = ''
     while ec != '--exit':
         ec = raw_input("Термин: ")
         if ec == '--exit':
             break
         db.delete("all_terms", [ec])
         db.commit()
     db.close_db()
Ejemplo n.º 11
0
 def UpdateUser(self, user_id):
     #db.loans.filter_by(db.loans.book_id==2).update({'book_id':1})
     userlevel = str(self._cboUserLevel.Text).split(" ")[0]
     Database.user.filter(Database.user.user_id == user_id).update({
         'firstname':
         self._txtFirstname.Text,
         'lastname':
         self._txtLastname.Text,
         'userlevel':
         userlevel
     })
     Database.commit()
     #Database.user.filter_by(Database.user.user_id==user_id).update({'lastname':self._txtLastname,'firstname':self._txtFirstname,'userlevel': userlevel})
     self.LoadUserData()
Ejemplo n.º 12
0
    def add_new_codes(codes):
        """
        Заносит правильные до этого момента не активированные коды в базу.
        user_id в таблице при этом проставляется случайный для имитации ввода кода пользователем.
        :param codes: Массив правильных кодов
        """

        records = []
        insert_query = "INSERT INTO activated_codes (code, user_id) VALUES (%s, %s);"
        db = Database()

        for code in codes:
            records.append((code, random.randint(1, 1000)))

        db.executemany(insert_query, records)
        db.commit()
Ejemplo n.º 13
0
    def DeleteUser(self, sender, e):
        # db.loans.delete(db.loans.book_id==2)
        # loan = db.loans.filter_by(book_id=2, user_name='Bhargan Basepair').one()
        # dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo);
        # if(dialogResult == DialogResult.Yes)
        # {
        #    //do something
        # }

        dlgResult = MessageBox.Show(
            "Are you sure you want to delete this user?", "Delete User", MessageBoxButtons.YesNo
        )
        if dlgResult == DialogResult.Yes:
            user = self.getUserInfo(self.current_user_id)
            # user = Database.user.filter(Database.user.user_id==3).one()
            Database.delete(user)
            Database.commit()
            self.LoadUserData()
            System.Windows.Forms.MessageBox.Show("Finished deleting..")
Ejemplo n.º 14
0
    def DeleteUser(self, sender, e):
        #db.loans.delete(db.loans.book_id==2)
        #loan = db.loans.filter_by(book_id=2, user_name='Bhargan Basepair').one()
        #dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo);
        #if(dialogResult == DialogResult.Yes)
        #{
        #    //do something
        #}

        dlgResult = MessageBox.Show(
            "Are you sure you want to delete this user?", "Delete User",
            MessageBoxButtons.YesNo)
        if (dlgResult == DialogResult.Yes):
            user = self.getUserInfo(self.current_user_id)
            #user = Database.user.filter(Database.user.user_id==3).one()
            Database.delete(user)
            Database.commit()
            self.LoadUserData()
            System.Windows.Forms.MessageBox.Show("Finished deleting..")
Ejemplo n.º 15
0
class UpdateDonate:
    def __init__(self, user_name, hosp_name, donation_val, donation_type, description):
        self.user_name = user_name
        self.hosp_name = hosp_name
        self.donation_val = donation_val
        self.donation_type = donation_type
        self.description = description
        self.db = Database()

    def add(self, root):
        try:
            cur = self.db.cursor
            cur.callproc("add_donation",
                         (self.user_name, self.hosp_name, self.donation_val, self.donation_type, self.description))
            self.db.commit()
            cur.close()
            showinfo(title="Success",
                     message="Thank you for your Donation!\n"
                             "You can now check it in your donation record.", parent=root)
        except pymysql.Error as e:
            print('Error: %d: %s' % (e.args[0], e.args[1]))
            showerror(title="Error",
                      message="You've already donated to this hospital. Please choose another.\n"
                              "If you want to update it, please check the history. Thanks.", parent=root)

    def remove(self, root):
        try:
            cur = self.db.cursor
            cur.callproc("remove_donation", (self.user_name, self.hosp_name))
            self.db.commit()
            cur.close()
            showinfo(title="Success", message="Cancelled successfully!", parent=root)
        except pymysql.Error:
            showerror(title="Error", message="Error occurs. Please try again.", parent=root)

    def update(self, root):
        try:
            cur = self.db.cursor
            cur.callproc("if_donated", (self.user_name, self.hosp_name))
            is_donated = cur.fetchone()

            if is_donated:
                # cur = self.db.cursor
                cur.callproc("update_donation",
                             (self.user_name, self.hosp_name, self.donation_val, self.donation_type, self.description))
                self.db.commit()
                cur.close()
                showinfo(title="Success",
                         message="Update successfully!", parent=root)
            else:
                showerror(title="Error",
                          message="You haven't donated for this hospital.", parent=root)

        except pymysql.Error as e:
            print('Error: %d: %s' % (e.args[0], e.args[1]))
            showerror(title="Error",
                      message="Error occurs. Please tried again.", parent=root)
Ejemplo n.º 16
0
class User(commands.Cog):
    def __init__(self, client):
        self._client = client
        self.db = Database()

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'User загружен.')

    @commands.command(name='personal-info',
                      aliases=['pi', 'личная-информация', 'лс'],
                      description=description.PERSONAL_INFO,
                      help=description.PERSONAL_INFO)
    @commands.has_permissions(send_messages=True)
    @commands.cooldown(1, 30, type=BucketType.user)
    async def personal_info(self, ctx):
        await ctx.message.delete()
        # Подключение происходит автоматически при импорте всех данных из database
        voice_min, messages, money = self.db.select_one(
            'users', ('voice_min', 'messages', 'money'), {
                'gid': ctx.guild.id,
                'uid': ctx.author.id
            })
        embed = discord.Embed(title='Личная информация',
                              description='',
                              timestamp=ctx.message.created_at,
                              colour=discord.Colour.from_rgb(255, 154, 0))
        embed.set_thumbnail(url=ctx.author.avatar_url)
        embed.add_field(name='Voice minutes:',
                        value=f'``{voice_min}``',
                        inline=False)
        embed.add_field(name='Messages:',
                        value=f'``{messages}``',
                        inline=False)
        embed.add_field(name='Money:', value=f'``{money}💵``', inline=False)
        await ctx.author.send(embed=embed)

    @personal_info.after_invoke
    async def reset_personal_info_cd(self, ctx):
        for role_id in WHITELIST:
            if role_id in [role.id for role in ctx.author.roles]:
                self.personal_info.reset_cooldown(ctx)

    @commands.command(name='level',
                      aliases=['show-level'],
                      description=description.USER_LEVEL,
                      help=description.USER_LEVEL)
    @commands.has_permissions(send_messages=True)
    @commands.cooldown(1, 30, type=BucketType.user)
    async def display_level(self, ctx, member: discord.Member = None):
        await ctx.message.delete()
        user = member or ctx.author
        exp, lvl = self.db.select_one('users', ('exp', 'lvl'), {
            'gid': ctx.guild.id,
            'uid': user.id
        })
        if lvl:
            await ctx.send(
                f'{user.display_name.mention} имеет {lvl} уровень с {exp}XP.')
        else:
            await ctx.send('У этого пользователя нет уровня.')

    @display_level.after_invoke
    async def reset_display_level_cd(self, ctx):
        for role_id in WHITELIST:
            if role_id in [role.id for role in ctx.author.roles]:
                self.display_level.reset_cooldown(ctx)

    @commands.command(name='balance',
                      aliases=['баланс'],
                      description=description.BALANCE,
                      help=description.BALANCE)
    @commands.has_permissions(send_messages=True)
    async def show_balance(self, ctx, member: discord.Member = None):
        await ctx.message.delete()
        user = member or ctx.author
        money, lvl, exp = self.db.select_one('users', ('money', 'lvl', 'exp'),
                                             {
                                                 'gid': ctx.guild.id,
                                                 'uid': user.id
                                             })
        embed = discord.Embed(description=f'**{user.display_name}**',
                              colour=ctx.author.colour)
        embed.set_thumbnail(url=user.avatar_url)
        embed.add_field(name='**💰Money Bag:**',
                        value=f'``{money}💵``',
                        inline=False)
        embed.add_field(name='**Уровень:**', value=f'``{lvl}``', inline=False)
        embed.add_field(name='**Опыт:**', value=f'``{exp}``', inline=False)
        await ctx.send(embed=embed)

    @commands.command(aliases=['daily', 'bonus', 'бонус'],
                      description=description.BONUS,
                      help=description.BONUS)
    @commands.has_permissions(send_messages=True)
    @commands.cooldown(1, 86400, type=BucketType.user)
    async def gives_out_a_bonus(self, ctx):
        money = self.db.select_one('users', ('money', ), {
            'gid': ctx.guild.id,
            'uid': ctx.author.id
        })[0]
        bonus = random.randint(10, 30)
        money += bonus
        self.db.update('users', {'money': money}, {
            'gid': ctx.guild.id,
            'uid': ctx.author.id
        })
        self.db.commit()
        await ctx.message.add_reaction('💸')

    @commands.command(aliases=['transfer', 'перевести', 'перевод'],
                      description=description.TRANSFER,
                      help=description.TRANSFER)
    @commands.has_permissions(send_messages=True)
    @commands.cooldown(1, 30, type=BucketType.user)
    async def transfers_money(self, ctx, member: discord.Member, amount: int):
        await ctx.messsage.delete()
        user_money = self.db.select_one('users', ('money', ), {
            'gid': ctx.guild.id,
            'uid': ctx.author.id
        })[0]  # Кто переводит
        client_money = self.db.select_one('users', ('money', ), {
            'gid': member.guild.id,
            'uid': member.id
        })[0]  # Кому переводят
        if amount < 0:
            raise errors.BadArgument
        else:
            user_money -= amount
            client_money += amount
            self.db.update('users', {'money': user_money}, {
                'gid': ctx.guild.id,
                'uid': ctx.author.id
            })
            self.db.update('users', {'money': client_money}, {
                'gid': member.guild.id,
                'uid': member.id
            })
            self.db.commit()

    @transfers_money.error
    async def transfer_error(self, ctx, error):
        if isinstance(error, errors.MissingRequiredArgument):
            embed = discord.Embed(
                description='Вы не определили необходимые аргументы.',
                colour=discord.Colour.red())
            embed.set_author(name=ctx.author.name,
                             icon_url=ctx.author.avatar_url)
            await ctx.send(embed=embed)
        if isinstance(error, errors.BadArgument):
            embed = discord.Embed(
                description='Укажите корректные данные.\n'
                'Кол-во валюты должно быть больше 0 или должно быть числом.',
                colour=discord.Colour.red())
            embed.set_author(name=ctx.author.name,
                             icon_url=ctx.author.avatar_url)
            await ctx.send(embed=embed)

    @transfers_money.after_invoke
    async def reset_transfer_cd(self, ctx):
        for role_id in WHITELIST:
            if role_id in [role.id for role in ctx.author.roles]:
                self.transfers_money.reset_cooldown(ctx)

    @staticmethod
    async def create_rand_emoji_num():
        nums = {
            0: '0️⃣',
            1: '1️⃣',
            2: '2️⃣',
            3: '3️⃣',
            4: '4️⃣',
            5: '5️⃣',
            6: '6️⃣',
            7: '7️⃣',
            8: '8️⃣',
            9: '9️⃣'
        }
        random.seed()
        return nums[random.randrange(len(nums))]

    @commands.command(name='roll',
                      aliases=['ролл', 'крутить', 'spin', 'rolling'],
                      description=description.ROLL,
                      help=description.ROLL)
    @commands.has_permissions(send_messages=True)
    @commands.cooldown(1, 5, type=BucketType.user)
    async def gen_rand_num(self, ctx):
        hundred, ten, one = await self.create_rand_emoji_num(
        ), await self.create_rand_emoji_num(
        ), await self.create_rand_emoji_num()
        await ctx.send('Роллиииммммм....', delete_after=3)
        await asyncio.sleep(3)
        await ctx.send(f'{hundred}{ten}{one}')

    @gen_rand_num.after_invoke
    async def reset_gen_rand_num_cd(self, ctx):
        for role_id in WHITELIST:
            if role_id in [role.id for role in ctx.author.roles]:
                self.gen_rand_num.reset_cooldown(ctx)

    @commands.command(name='spoiler',
                      aliases=['спойлер'],
                      description=description.SPOILER,
                      help=description.SPOILER)
    @commands.has_permissions(send_messages=True)
    @commands.cooldown(1, 5, type=BucketType.user)
    async def create_spoiler(self, ctx, *, text: str):
        await ctx.message.delete()
        await ctx.send(f'||{text}||')

    @create_spoiler.after_invoke
    async def reset_create_spoiler_cd(self, ctx):
        for role_id in WHITELIST:
            if role_id in [role.id for role in ctx.author.roles]:
                self.create_spoiler.reset_cooldown(ctx)
Ejemplo n.º 17
0
    def parse_files(self):
        """
        Производит парсинг файлов из директории "input/".
        Сохраняет результат в БД.
        """

        # словари терминов и фраз по всем файлам
        all_terms = []
        all_phrases = []

        # создаёт список файлов
        files_in_dir = os.listdir(self.input_path)
        for file_name in files_in_dir:

            # парсит файл на термины. возврашает список
            parsed_terms = self.parse_terms(self.input_path + file_name)
            # парсит файл на фразы
            parsed_phrases = self.parse_phrases(self.input_path + file_name)

            # заполняет all_terms из каждого отпарсенного файла
            for term in parsed_terms:
                if term not in all_terms:
                    all_terms.append(term)
            # заполняет all_phrases
            for phrase in parsed_phrases:
                # проверку на совпадение фраз не вижу смысла делать
                all_phrases.append(phrase)

            #os.remove(self.input_path + file_name)

            # удаляю термины имеющиеся в useless_terms
            # возвращает словарь без useless терминов
            without_useless = self.check_on_useless(all_terms)

            # таблицы на обновление
            phrases_objs = {
                "parsed_phrases": all_phrases,
            }

            terms_objs = {
                "parsed_terms": without_useless,
                "useless_terms": without_useless
            }

            # сохраняет новые термины в таблицу parsed_terms
            # сохраняет новые фразы в таблицу parsed_phrases
            # обновляет таблицу useless_terms
            if all_phrases:
                db = Database(file_name[:-3] + 'db')
                db.create_tables(PHRASES_TABLES)
                for table in phrases_objs:
                    for row in phrases_objs[table]:
                        row = [row]
                        db.insert(table, row)
                db.commit()
                db.close_db()

            if without_useless:
                db = Database("terms.db")
                for table in terms_objs:
                    for row in terms_objs[table]:
                        row = [row]
                        db.insert(table, row)
                db.commit()
                db.close_db()
Ejemplo n.º 18
0
class Casino(commands.Cog):
    def __init__(self, client):
        self._client = client
        self.db = Database()
        self._range = ['1-2', '3-4', '5-6', '7-8']
        self.error = discord.Colour.red()
        self.black = discord.Colour.from_rgb(0, 0, 0)
        self.arrows = {
            1: '↖',
            2: '⬆',
            3: '↗',
            4: '➡',
            5: '↘',
            6: '⬇',
            7: '↙',
            8: '⬅'
        }

    async def displays_error(self, message, desc):
        embed = discord.Embed(description=desc, colour=self.error)
        embed.set_author(name=message.author.name,
                         icon_url=message.author.avatar_url)
        await message.channel.send(embed=embed)

    def create_embed(self,
                     rate: int,
                     is_win: bool,
                     arrow,
                     factor: float = None,
                     winnings: float = None,
                     money: float = None):
        nums = {
            1: '1️⃣',
            2: '2️⃣',
            3: '3️⃣',
            4: '4️⃣',
            5: '5️⃣',
            6: '6️⃣',
            7: '7️⃣',
            8: '8️⃣'
        }
        embed = discord.Embed(title='Casino',
                              description='',
                              colour=self.black)
        data = [
            ('**Ставка:**', rate, True),
            (f'{"**Остаток на счете:**" if factor is None else "**Множитель:**"}',
             f'{money if factor is None else factor}', False),
            (f'{"**Выигрыш:**" if is_win else "**Проигрыш:**"}',
             f'{"**Не везет, попробуй еще раз!**" if not is_win else winnings}',
             False),
            ('**Рулетка**',
             f'{nums[1]}{nums[2]}{nums[3]}\n{nums[8]}{arrow}{nums[4]}\n{nums[7]}{nums[6]}{nums[5]}',
             False)
        ]
        for name, value, inline in data:
            embed.add_field(name=name, value=f'{value}', inline=inline)
        return embed

    @staticmethod
    def counts_zeros(num: Union[int, float]):
        after_comma = [int(n) for n in str(num).split('.')[-1]]
        return after_comma

    def returns_a_random_arrow(self):
        random.seed()
        key = random.randrange(1, len(self.arrows) + 1)
        arrow = self.arrows[key]
        return arrow

    def calculates(self,
                   money,
                   is_win: bool,
                   arrow: str,
                   rate: Union[int, float],
                   factor: Union[int, float] = None):
        if is_win:
            winnings = rate * factor
            money += winnings
            embed = self.create_embed(rate, is_win, arrow, factor, winnings)
        else:
            money -= rate  # Текущий баланс, с учетом ставки.
            embed = self.create_embed(rate, is_win, arrow, money=money)
        return embed

    @commands.command(name='casino',
                      aliases=['казино'],
                      description=description.CASINO,
                      help=description.CASINO)
    @commands.has_permissions(send_messages=True)
    @commands.cooldown(1, 5, type=BucketType.user)
    async def show_casino(self, ctx, _range: str, rate: Union[int, float]):
        money = self.db.select_one('users', ('money', ), {
            'gid': ctx.guild.id,
            'uid': ctx.author.id
        })[0]
        after_comma = self.counts_zeros(rate)
        if _range not in self._range:
            await self.displays_error(
                ctx.message,
                f'Введенный диапазон({_range}) не соответствует ни одному из возможных({self._range}).'
            )
        if rate is None or not isinstance(
                rate,
            (int, float)) or rate < 0 or money < rate or len(after_comma) > 2:
            raise errors.BadArgument
        arrow = self.returns_a_random_arrow()
        if _range == '1-2' and (arrow == self.arrows[1]
                                or arrow == self.arrows[2]):
            embed_ = self.calculates(money, True, arrow, rate, 1.5)
        elif _range == '3-4' and (arrow == self.arrows[3]
                                  or arrow == self.arrows[4]):
            embed_ = self.calculates(money, True, arrow, rate, 2)
        elif _range == '5-6' and (arrow == self.arrows[5]
                                  or arrow == self.arrows[6]):
            embed_ = self.calculates(money, True, arrow, rate, 3)
        elif _range == '7-8' and (arrow == self.arrows[7]
                                  or arrow == self.arrows[8]):
            embed_ = self.calculates(money, True, arrow, rate, 5)
        else:
            embed_ = self.calculates(money, False, arrow, rate)
        await ctx.send(embed=embed_)
        self.db.update('users', {'money': money}, {
            'gid': ctx.guild.id,
            'uid': ctx.author.id
        })
        self.db.commit()

    @show_casino.error
    async def show_casino_error(self, ctx, error):
        if isinstance(error, errors.MissingRequiredArgument):
            await self.displays_error(ctx.message, desc_errors['miss_req_arg'])
        if isinstance(error, errors.BadArgument):
            await self.displays_error(
                ctx.message,
                'Укажите корректные данные.\n'
                'Введена некорректная ставка(пример ставки: 100.15).\n'
                'Ставка должна быть больше 0 или должна быть числом.',
            )

    @commands.Cog.listener()
    async def on_ready(self):
        print('Casino загружен.')
Ejemplo n.º 19
0
class Login:
    def __init__(self):
        self.db = Database()

        self.login = Tk()
        self.login.resizable(0, 0)
        self.login.title("Covid Tracker")

        screenwidth = self.login.winfo_screenwidth()
        screenheight = self.login.winfo_screenheight()
        width = 500
        height = 300
        self.login.geometry("%dx%d+%d+%d" % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2))

        self.canvas = Canvas(self.login, height=300, width=500)
        self.file = PhotoImage(file="covid_tracker.png")
        self.image = self.canvas.create_image(0, 0, anchor=CENTER, image=self.file)
        self.canvas.pack(side="top")

        Label(self.login, text="username").place(relx=0.2, y=70)
        Label(self.login, text="password").place(relx=0.2, y=95)

        username = StringVar()
        password = StringVar()

        Entry(self.login, width=30, textvariable=username).place(relx=0.37, y=70)
        Entry(self.login, width=30, show="*", textvariable=password).place(relx=0.37, y=95)

        # using lambda to allow passing arguments in Tk Button's command
        Button(self.login, text="Login", width=10,
               command=lambda: self.login_check(username, password)).place(relx=0.3, y=200)
        Button(self.login, text="Register", width=10,
               command=lambda: self.register(username, password)).place(relx=0.5, y=200)

        mainloop()

    def login_check(self, username, password):
        username = username.get()
        password = password.get()
        cur = self.db.cursor
        if not (len(username) == 0 or len(password) == 0):
            query = "SELECT user_password FROM user_account WHERE user_name=%s"
            cur.execute(query, username)
            result = cur.fetchone()
            if result:
                if password == result['user_password']:
                    showinfo(title="Welcome", message="Logged in successfully!")
                    self.login.destroy()
                    MainView(username)
                    cur.close()
                else:
                    showerror(title="Error", message="Unmatched username and password!")
            else:
                showwarning(title="Warning", message="Username does not exist. Please register first.")
        else:
            showerror(title="Error", message="Username or password cannot be empty.")

    def register(self, username, password):
        username = username.get()
        password = password.get()
        cur = self.db.cursor
        if not (len(username) == 0 or len(password) == 0):
            if ' ' in username:
                showerror(title="Error", message="Username cannot contain space.")
            else:
                cur.callproc("initialize_user_account", (username, password))
                self.db.commit()
                showinfo(title="Success", message="Congratulations! Register Done.")
        else:
            showerror(title="Error", message="Username or password cannot be empty.")
Ejemplo n.º 20
0
def record_message(db: Database, msg):
    '''Add message info to the database'''
    db.get().execute(
        "INSERT INTO messages(author, date, channel_id, message_id) VALUES(?, datetime('now', 'utc'), ?, ?);",
        (msg.author.id, msg.channel.id, msg.id))
    db.commit()
Ejemplo n.º 21
0
class TestDatabase(unittest.TestCase):
	def setUp(self):
		self.db = Database()
		
	def test_get_and_set(self):
		self.db.set('a', 10)

		self.assertEqual(self.db.get('a'), 10)

	def test_get_null(self):
		self.assertEqual(self.db.get('nonexistant'), 'NULL')

	def test_unset(self):
		self.db.set('a', 10)

		self.db.unset('a')

		self.assertEqual(self.db.get('a'), 'NULL')

	def test_equalto(self):
		self.db.set('a', 10)
		self.db.set('c', 10)
		self.db.set('b', 10)

		self.assertEqual(self.db.equalto(10), 'a b c')

	def test_equalto_none(self):
		self.assertEqual(self.db.equalto(10), 'NONE')

	def test_equalto_unset(self):
		self.db.set('a', 10)
		self.db.set('c', 10)
		self.db.set('b', 10)

		self.db.unset('b')

		self.assertEqual(self.db.equalto(10), 'a c')

	def test_equalto_change(self):

		self.db.set('a', 10)
		self.db.set('a', 20)

		self.assertEqual(self.db.equalto(10), 'NONE')
		self.assertEqual(self.db.equalto(20), 'a')

	def test_program(self):
		"""SET a 10
		SET b 10
		EQUALTO 10
		EQUALTO 20
		UNSET a
		EQUALTO 10
		SET b 30
		EQUALTO 10"""

		self.db.set('a', 10)
		self.db.set('b', 10)

		self.assertEqual(self.db.equalto(10), 'a b')
		self.assertEqual(self.db.equalto(20), 'NONE')

		self.db.unset('a')

		self.assertEqual(self.db.equalto(10), 'b')

		self.db.set('b', 30)

		self.assertEqual(self.db.equalto(10), 'NONE')

	def test_tx_commit(self):
		self.db.set('a', 10)

		self.db.begin()

		self.assertEqual(self.db.get('a'), 10)

		self.db.set('a', 20)

		self.assertEqual(self.db.get('a'), 20)

		self.db.commit()

		self.assertEqual(self.db.get('a'), 20)

	def test_tx_full_commit(self):

		# test that commit commits *all* open transactions
		self.db.begin()
		self.db.set('a', 30)
		self.db.begin()
		self.db.set('a', 40)
		self.db.commit()
		self.assertEqual(self.db.get('a'), 40)
		self.assertEqual(self.db.rollback(), 'INVALID ROLLBACK')

	def test_tx_rollback(self):

		self.db.set('a', 10)

		self.db.begin()

		self.assertEqual(self.db.get('a'), 10)

		self.db.set('a', 20)

		self.assertEqual(self.db.get('a'), 20)

		self.db.rollback()

		self.assertEqual(self.db.get('a'), 10)

	def test_tx_invalid_rollback(self):
		self.assertEqual(self.db.rollback(), 'INVALID ROLLBACK')

	def test_tx_begin_rollback_commit(self):
		self.db.set('a', 50)
		self.db.begin()
		self.assertEqual(self.db.get('a'), 50)
		self.db.set('a', 60)
		self.db.begin()
		self.db.unset('a')
		self.assertEqual(self.db.get('a'), 'NULL')
		self.db.rollback()
		self.assertEqual(self.db.get('a'), 60)
		self.db.commit()
		self.assertEqual(self.db.get('a'), 60)
Ejemplo n.º 22
0
class RecBySNS(object):
    def __init__(self):
        self.db = Database()
        self.nlpir = PyNLPIR(self)
        self.renren = Renren(self)
        self.url = URL(self)
        self.UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv: 17.0) Gecko/17.0 Firefox/17.0"
        self.pos_blacklist_regexs = [
            "^emoticon$",
            "^title$",
            "^ude.",
            "^w.*",
            "^vshi",
            "^vyou",
            "^p.*",
            "^ule",
            "^m.*",
            "^cc",
            "^session$",
        ]

    def assign_recbysns_entity_sentiment(self):
        for status in self.db.select_table(
            "weibo_status",
            "text like '%%《%%》%%' or \
                                            text like '%%http://%%' or \
                                            text like '%%https://%%'",
            12696,
            5,
        ):
            sessions = self.nlpir.segment_weibo_status(status["text"])
            i = 0
            while i < len(sessions):
                session = sessions[i]
                entities = []
                session_text = ""
                for segment in session:
                    session_text += segment.rsplit("/", 1)[0]
                    if self.nlpir.get_POS(segment) == "title":
                        title = re.match(u"《(.*?)》/title", segment).group(1)
                        if self.db.select_douban_movie_by_title(title) or self.db.select_douban_book_by_title(title):
                            entities.append(segment)
                    elif self.nlpir.get_POS(segment) == "url":
                        match = re.search(u"(http.*)/url", segment)
                        if match is None:
                            print "###########%s###########" % segment
                            continue
                        url = match.group(1)
                        url = self.db.select_recbysns_url_by_short_url(url)
                        if url is None:
                            print "***********%s***********" % segment
                            continue
                        if self.url.is_video_url(url["origin_url"]):
                            entities.append(segment)
                positions = {}
                for entity in entities:
                    if entity in positions:
                        position = positions[entity] + 1
                        positions[entity] = position
                    else:
                        position = 0
                        positions[entity] = position
                    print status["text"]
                    print session_text
                    print entity
                    print "Type:"
                    type = int(sys.stdin.readline())
                    print "Sentiment:"
                    sentiment = int(sys.stdin.readline())
                    self.db.query(
                        "INSERT INTO recbysns_entity( \
                                   entity, status_id, session, position, \
                                   type, score) \
                                   VALUES(%s, %s, %s, %s, %s, %s)",
                        (entity, status["id"], i, position, type, sentiment),
                    )
                    self.db.commit()
                i = i + 1

    def is_blacklist_word(self, word):
        for pos_blacklist_regex in self.pos_blacklist_regexs:
            if re.search(pos_blacklist_regex, self.nlpir.get_POS(word)):
                return True
        return False
Ejemplo n.º 23
0
class Events(commands.Cog):
    def __init__(self, client):
        self._client = client
        self.db = Database()

    async def changes_status(self, guild):
        await self._client.change_presence(activity=discord.Activity(
            type=discord.ActivityType.watching,
            name=f'за сервером |\nУчастников: {len(guild.members)}'),
                                           status=discord.Status.idle)

    @staticmethod
    async def sets_prefix(guild):
        with open('prefixes.json') as f:
            prefixes = json.load(f)

        prefixes[str(guild.id)] = str(settings['prefix'])

        with open('prefixes.json', 'w') as f:
            json.dump(prefixes, f, indent=4)

    @staticmethod
    async def remove_prefix(guild):
        with open('prefixes.json') as f:
            prefixes = json.load(f)

        prefixes.pop(str(guild.id))

        with open('prefixes.json', 'w') as f:
            json.dump(prefixes, f, indent=4)

    @commands.Cog.listener()
    async def on_ready(self):
        print('Events загружен.')
        self.db.creates_tables()
        for guild in self._client.guilds:
            guild_on_the_table = self.db.select_one('guilds', ('id', ),
                                                    {'id': guild.id})
            await self.changes_status(guild)
            if not guild_on_the_table:
                await self.sets_prefix(guild)
                self.db.insert_many(
                    'guilds', {
                        'id': guild.id,
                        'name': guild.name,
                        'owner_id': guild.owner_id,
                        'owner_name': guild.owner.name
                    })

            for member in guild.members:
                member_in_the_table = self.db.select_one(
                    'users', ('uid', ), {
                        'gid': guild.id,
                        'uid': member.id
                    })
                if not member_in_the_table:
                    roles = ' '.join([role.name for role in member.roles][1:])
                    self.db.insert_many('users', {
                        'gid': guild.id,
                        'uid': member.id,
                        'roles': str(roles)
                    })
        self.db.commit()

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return

        embed = discord.Embed()
        if message.content.isupper():
            await message.delete()
            embed.set_author(name=message.author.name,
                             icon_url=message.author.avatar_url)
            embed.description = 'Пожалуйста, не используйте Caps Lock в своих сообщениях!'
            embed.colour = discord.Colour.red()
            await message.channel.send(embed=embed, delete_after=10)

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        if isinstance(error, errors.CommandOnCooldown):
            date = '{:<8}'.format(
                str(timedelta(seconds=round(error.retry_after))))
            embed = discord.Embed(
                description='Вы еще не можете использовать эту команду!\n'
                f'Пожалуйста, подождите {date}c.')
            await ctx.send(embed=embed)

    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        result = self.db.select_one('guilds', ('id', ), {'id': guild.id})
        if not result:
            await self.sets_prefix(guild)
            self.db.insert_many(
                'guilds', {
                    'id': guild.id,
                    'name': guild.name,
                    'owner_id': guild.owner_id,
                    'owner_name': guild.owner.name
                })
            self.db.commit()

    @commands.Cog.listener()
    async def on_guild_remove(self, guild):
        await self.remove_prefix(guild)
        self.db.delete(
            'guilds', {'id': guild.id}
        )  # FIXME удаляется только с определенной таблицы, а удалять нужно все
        self.db.commit()
        print('Покинул гильдию')

    @commands.Cog.listener()
    async def on_member_join(self, member):
        result = self.db.select_one('users', ('uid', ), {
            'gid': member.guild.id,
            'uid': member.id
        })
        if not result:
            channel = member.guild.get_channel(channel_id=WELCOME_CHANNEL)
            role = discord.utils.get(member.guild.roles, id=724366698827874396)
            self.db.insert_many('users', {
                'gid': member.guild.id,
                'uid': member.id,
                'roles': str(role)
            })
            await channel.send(f'{member.mention}, {choice(greetings)}')
            await member.add_roles(role)
            self.db.commit()

    @commands.Cog.listener()
    async def on_member_remove(self, member):
        self.db.delete('users', {'gid': member.guild.id, 'uid': member.id})
        self.db.commit()
        print(f'{member} покинул гильдию!')

    @commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        for guild in self._client.guilds:
            if after.channel.id == 732118857271083128:
                category = discord.utils.get(guild.categories,
                                             id=732118116733288499)
                room = await guild.create_voice_channel(name=member.name,
                                                        category=category)
                await room.set_permissions(member,
                                           connect=True,
                                           move_members=True,
                                           manage_channels=True)
                await member.move_to(room)

                def check():
                    return len(room.members) == 0

                await self._client.wait_for('voice_state_update', check=check)
                await room.delete()
Ejemplo n.º 24
0
class Shop(commands.Cog):
    def __init__(self, client):
        self._client = client
        self.db = Database()
        self.error = discord.Colour.red()  # Цвет embed ошибки

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'Shop загружен.')

    async def displays_error(self, message, description):
        embed = discord.Embed(description=description, colour=self.error)
        embed.set_author(name=message.author.name,
                         icon_url=message.author.avatar_url)
        await message.channel.send(embed=embed)

    def create_embed(self, title, description, isthumbnail: bool = True):
        embed = discord.Embed(title=title,
                              description=description,
                              colour=discord.Colour.from_rgb(255, 154, 0))
        if isthumbnail:
            embed.set_thumbnail(url=self._client.user.avatar_url)
        return embed

    async def insert_into_shops(self, ctx, title, description):
        self.db.insert_many('shops', {
            'gid': ctx.guild.id,
            'name': title,
            'description': description
        })
        embed = self.create_embed(f'Магазин {title}', description)
        await ctx.send(embed=embed, delete_after=10)
        await ctx.send('Пора добавлять товары в магазин.', delete_after=10)

    @commands.command(name='create-shop',
                      aliases=['new-market', 'build-store'])
    @commands.has_any_role(owner_role_id, deputy_role_id, admin_role_id)
    async def creates_a_store(
            self,
            ctx,
            title: str,
            description: str = 'Добро пожаловать в Hydrargyrum Hype Shop.'):
        shop = self.db.select_one('shops', ('id', ), {
            'gid': ctx.guild.id,
            'name': title
        })
        if not shop:
            if len(title) < 3:
                raise errors.BadArgument
            else:
                await self.insert_into_shops(ctx, title, description)
        self.db.commit()

    @creates_a_store.error
    async def creates_a_store_error(self, ctx, error):
        if isinstance(error, errors.MissingAnyRole):
            await self.displays_error(ctx.message,
                                      desc_errors['miss_any_role'])
        if isinstance(error, errors.MissingRequiredArgument):
            await self.displays_error(ctx.message, desc_errors['miss_req_arg'])
        if isinstance(error, errors.BadArgument):
            await self.displays_error(ctx.message, desc_errors['need_more'])

    @commands.command(name='add-product',
                      aliases=['add-item', 'добавить-продукт'])
    @commands.has_any_role(owner_role_id, deputy_role_id, admin_role_id)
    async def adds_product(self, ctx, title: str, price: int, *, name: str):
        if price < 0 or len(name) < 3:
            raise errors.BadArgument
        else:
            sid = self.db.select_one('shops', ('id', ), {
                'gid': ctx.guild.id,
                'name': title
            })  # [0]
            if not sid:
                raise exceptions.ShopNotFound
            else:
                item = self.db.select_one('products', ('id', ), {
                    'gid': ctx.guild.id,
                    'sid': sid[0],
                    'name': name
                })
                if not item:
                    self.db.insert_many(
                        'products', {
                            'gid': ctx.guild.id,
                            'sid': sid[0],
                            'price': price,
                            'name': name
                        })

                    with open('prefixes.json') as f:
                        prefixes = json.load(f)
                    prefix = prefixes[str(ctx.guild.id)]

                    embed = self.create_embed(title='Товар добален.',
                                              description='',
                                              isthumbnail=False)
                    embed.set_footer(
                        text=
                        f'Чтобы увидеть товары, введи {prefix}shop {title}',
                        icon_url=ctx.author.avatar_url)
                    await ctx.send(embed=embed, delete_after=10)
            self.db.commit()

    @adds_product.error
    async def adds_product_error(self, ctx, error):
        if isinstance(error, errors.MissingAnyRole):
            await self.displays_error(ctx.message,
                                      desc_errors['miss_any_role'])
        if isinstance(error, errors.MissingRequiredArgument):
            await self.displays_error(ctx.message, desc_errors['miss_req_arg'])
        if isinstance(error, errors.BadArgument):
            await self.displays_error(ctx.message, desc_errors['need_more+'])
        if isinstance(error, exceptions.ShopNotFound):
            await self.displays_error(ctx.message,
                                      desc_errors['shop_not_found'])

    @commands.command(name='shop', aliases=['market', 'store', 'магазин'])
    @commands.has_permissions(send_messages=True)
    @commands.cooldown(1, 5, type=BucketType.user)
    async def display_shop(self, ctx, title: str):
        sid, description = self.db.select_one('shops', ('id', 'description'), {
            'gid': ctx.guild.id,
            'name': title
        })
        products = self.db.select_many('products', ('name', 'price'), {
            'gid': ctx.guild.id,
            'sid': sid
        })
        if not sid:
            raise exceptions.ShopNotFound
        else:
            embed = self.create_embed(title, description)
            for product in products:
                name, price = product
                embed.add_field(name=f'Название: __``{name}``__',
                                value=f'Цена: **``{price}``**',
                                inline=False)
            await ctx.send(embed=embed)

    @display_shop.error
    async def display_shop_error(self, ctx, error):
        if isinstance(error, errors.MissingRequiredArgument):
            await self.displays_error(ctx.message, desc_errors['miss_req_arg'])
        if isinstance(error, exceptions.ShopNotFound):
            await self.displays_error(ctx.message,
                                      desc_errors['shop_not_found'])

    @display_shop.after_invoke
    async def reset_display_shop_cd(self, ctx):
        for role_id in WHITELIST:
            if role_id in [role.id for role in ctx.author.roles]:
                self.display_shop.reset_cooldown(ctx)
Ejemplo n.º 25
0
class Douban(object):
    def __init__(self):
        self.client = \
            DoubanClient('028bc5c2b034fb1c07a35148109ef154',
                         '2f42bec4d6a403b4',
                         'http://rec.jjyao.me',
                         'douban_basic_common,shuo_basic_r,shuo_basic_w')
        #self.client.auth_with_code('39076cd663a27f06')
        from recbysns import recbysns
        self.recbysns = recbysns
        self.db = Database()
        self.cookie = 'bid="feXKjUDU9TI"; ue="*****@*****.**"; ll="118159"; ct=y; viewed="10001392_4025068_3098478_3302642_1434275_21760836_10537640_10522595_6799191"; dbcl2="51087586:lfMA83G6vyc"; ck="hW6b"; __utma=30149280.1374624205.1362216082.1368805078.1368838128.94; __utmb=30149280.31.10.1368838128; __utmc=30149280; __utmz=30149280.1368798357.92.42.utmcsr=movie.douban.com|utmccn=(referral)|utmcmd=referral|utmcct=/subject/11529526/; __utmv=30149280.5108; __utma=81379588.1127088638.1342424134.1368807092.1368838128.118; __utmb=81379588.52.8.1368843871481; __utmc=81379588; __utmz=81379588.1368798357.115.34.utmcsr=movie.douban.com|utmccn=(referral)|utmcmd=referral|utmcct=/subject/11529526/'

    def __getattr__(self, attr):
        return _Callable(self, attr, getattr(self.client, attr))

    def book_search(self, **kw):
        """ Fallback for book.search """
        keyword = kw['q']
        books = []
        for i in [0, 15]:
            url = 'http://book.douban.com/subject_search?start=%d&search_text=%s&cat=1001' % \
                  (i, keyword.encode('utf-8'))
            html = pq(url=url, parser='html', opener=lambda url, **kw:
                      urllib2.urlopen(urllib2.Request(url, headers={
                            'User-Agent': self.recbysns.UA,
                            'Cookie': self.cookie}), timeout=10).read().
                            decode('utf8', 'ignore'))
            for book in html('#content .subject-list .subject-item'):
                book = pq(book)
                collect_info = book('.info .collect-info span')
                # I have not read the book
                if len(collect_info) > 1:
                    state = pq(collect_info[1]).text()
                    if state == u'经常读':
                        continue
                book_id = int(re.match('http://book.douban.com/subject/(\d+)/',
                              book('.pic .nbg').attr('href')).group(1))
                title = book('.info h2 a').attr('title')
                image = book('.pic .nbg img').attr('src')
                pub = book('.info .pub').text()
                rating = pq(book('.info .star'))
                if rating('.rating_nums'):
                    numRaters = int(re.match(u'\((\d+)',
                                    rating('.pl').text()).group(1))
                    average = rating('.rating_nums').text()
                    rating = {"numRaters": numRaters, "average": average}
                else:
                    rating = {"numRaters": 0, "average": 0}
                books.append({'id': book_id, 'title': title,
                              'image': image, 'pub': pub, 'rating': rating})
        return {'books': books, 'total': len(books)}

    def movie_search(self, **kw):
        """ Fallback for movie.search """
        keyword = kw['q']
        url = 'http://movie.douban.com/subject_search?search_text=%s&cat=1002' % \
              keyword.encode('utf-8')
        html = pq(url=url, parser='html', opener=lambda url, **kw:
                    urllib2.urlopen(urllib2.Request(url, headers={
                        'User-Agent': self.recbysns.UA,
                        'Cookie': self.cookie}), timeout=10).read())
        movies = []
        for movie in html('#content table .item'):
            movie = pq(movie)
            id = int(re.match('http://movie.douban.com/subject/(\d+)/',
                     movie('.nbg').attr('href')).group(1))
            image = movie('.nbg img').attr('src')
            pub = movie('.pl2>.pl').text()
            rating = pq(movie('.pl2 .star'))
            if rating and rating('.rating_nums').text():
                numRaters = int(re.match(u'\((\d+)',
                                rating('.pl').text()).group(1))
                average = rating('.rating_nums').text()
                rating = {"numRaters": numRaters, "average": average}
            else:
                rating = {"numRaters": 0, "average": 0}
            titles = [title.strip()
                      for title in movie('.pl2>a').text().split('/')]
            movies.append({'id': id, 'titles': titles,
                           'image': image, 'pub': pub, 'rating': rating})
        return {'movies': movies, 'total': len(movies)}

    def crawl_book(self):
        #start = 63831 %《%》%
        for book in self.db.select_table('douban_book', 'img_url is null'):
            try:
                result = douban.book.search(q=book['title'])
                if int(result['total']) == 0:
                    print book['title']
                    continue
                for result in result['books']:
                    if result['title'] == book['title']:
                        self.db.query("UPDATE douban_book SET id = %s, \
                                      img_url = %s, pub = %s, \
                                      raters_num = %s, score = %s \
                                      WHERE id = %s",
                                      (result['id'], result['image'],
                                       result['pub'],
                                       result['rating']['numRaters'],
                                       result['rating']['average'],
                                       book['id']))
                        self.db.commit()
                        break
            except Exception as e:
                print book['title']
                print e

    def crawl_movie(self):
        for movie in self.db.select_table('douban_movie', 'img_url is null'):
            try:
                result = douban.movie.search(q=movie['title'])
                if int(result['total']) == 0:
                    print movie['title']
                    continue
                for result in result['movies']:
                    if movie['title'] in result['titles']:
                        self.db.query("UPDATE douban_movie SET id = %s, \
                                       img_url = %s, pub = %s, \
                                       raters_num = %s, score = %s \
                                       WHERE id = %s",
                                       (result['id'], result['image'],
                                        result['pub'],
                                        result['rating']['numRaters'],
                                        result['rating']['average'],
                                        movie['id']))
                        self.db.commit()
                        break
            except Exception as e:
                print movie['title']
                print e
Ejemplo n.º 26
0
class Exp(commands.Cog):
    def __init__(self, client):
        self._client = client
        self.db = Database()
        self.regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([" \
                     r"^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
        self.adds_time_for_voice_min.start()
        self.places = ["🥇", "🥈", "🥉", "🏅"]
        self.patterns = ['messages', 'voice_min', 'money', 'lvl']

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'Exp загружен.')

    async def adds_data(self, guild, user):
        user_in_the_table = self.db.select_one('users', ('uid', ), {
            'gid': guild.id,
            'uid': user.id
        })
        if not user_in_the_table:
            role = discord.utils.get(user.guild.roles, id=724366698827874396)
            self.db.insert_many('users', {
                'gid': guild.id,
                'uid': user.id,
                'roles': str(role)
            })
            self.db.commit()

    async def add_experience(self, guild, user, exp):
        if not user.bot:
            user_exp = self.db.select_one('users', ('exp', ), {
                'gid': guild.id,
                'uid': user.id
            })[0]
            user_exp += exp
            self.db.update('users', {'exp': user_exp}, {
                'gid': guild.id,
                'uid': user.id
            })
            self.db.commit()

    async def level_up(self, guild, user, channel):
        if not user.bot:
            exp = self.db.select_one('users', ('exp', ), {
                'gid': guild.id,
                'uid': user.id
            })[0]
            current_lvl = self.db.select_one('users', ('lvl', ), {
                'gid': guild.id,
                'uid': user.id
            })[0]
            next_lvl = int(exp**(1 / 4))

            if current_lvl < next_lvl:
                await channel.send(
                    f'{user.mention} поднялся! Теперь у него {next_lvl} уровень!',
                    delete_after=10)
                self.db.update('users', {'lvl': next_lvl}, {
                    'gid': guild.id,
                    'uid': user.id
                })
                self.db.commit()

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return

        if message.channel.id not in [CHAT_CHANNEL,
                                      GIVEAWAYS_CHANNEL] and re.search(
                                          self.regex, message.content):
            await message.delete()
            await message.channel.send(
                'Ты не можешь отправлять ссылки в этом канале.',
                delete_after=10)

        if message.channel.id not in [COMMAND_CHANNEL, GIVEAWAYS_CHANNEL]:
            count_of_msg, money = self.db.select_one(
                'users', ('messages', 'money'), {
                    'gid': message.guild.id,
                    'uid': message.author.id
                })
            count_of_msg += 1
            money += gives_out_coins()
            self.db.update('users', {
                'money': money,
                'messages': count_of_msg
            }, {
                'gid': message.guild.id,
                'uid': message.author.id
            })
            self.db.commit()

            await self.adds_data(message.guild, message.author)
            await self.add_experience(message.guild, message.author, 1)
            await self.level_up(message.guild, message.author, message.channel)

        if message.channel.id not in [CHAT_CHANNEL, GIVEAWAYS_CHANNEL] and any(
            [hasattr(attach, 'width') for attach in message.attachments]):
            await message.delete()

    def cog_unload(self):
        self.adds_time_for_voice_min.cancel()

    @tasks.loop(minutes=1)
    async def adds_time_for_voice_min(self):
        if len(self._client.guilds) == 0:
            return
        for guild in self._client.guilds:
            for voice_channel in guild.voice_channels:
                # FIXME исправить на len() > 1 для того, чтобы не было накрутки монет
                if voice_channel.id != 723635991646306306 and len(
                        voice_channel.members) > 0:
                    for member in voice_channel.members:
                        voice_min, money = self.db.select_one(
                            'users', ('voice_min', 'money'), {
                                'gid': member.guild.id,
                                'uid': member.id
                            })
                        voice_min += 1
                        money += gives_out_coins()
                        await self.add_experience(member.guild.id, member.id,
                                                  1)
                        self.db.update('users', {
                            'money': money,
                            'voice_min': voice_min
                        }, {
                            'gid': member.guild.id,
                            'uid': member.author.id
                        })
                        self.db.commit()

    @adds_time_for_voice_min.before_loop
    async def before_talk(self):
        print('waiting...')
        await self._client.wait_until_ready()

    @commands.command(aliases=['top'],
                      descripition=description.LEADERS,
                      help='``Выводит лучших пользователей.``')
    @commands.has_permissions(send_messages=True)
    @commands.cooldown(1, 30, type=BucketType.user)
    async def shows_leaders(self, ctx, pattern: str = 'messages'):
        user = ctx.author
        if pattern in self.patterns:
            top_users = self.db.select_many(
                'users', ('user_id', 'money', 'lvl', 'messages', 'voice_min'),
                {'gid': user.guild.id}, f'ORDER BY {pattern} DESC')[:10]
            embed = discord.Embed(title='Leaders',
                                  description='',
                                  colour=user.colour)
            for pos, writer in enumerate(top_users, 1):
                user_id, money, lvl, messages, voice_min = writer
                user = self._client.get_user(user_id)
                if pos < 4:
                    adds_a_field(embed, pos, user, self.places[pos], money,
                                 voice_min, messages, lvl)
                else:
                    adds_a_field(embed, pos, user, self.places[-1], money,
                                 voice_min, messages, lvl)
            await ctx.send(embed=embed)
        else:
            embed = discord.Embed(description=f'{self.patterns}')
            await ctx.send('Укажите корректный тип сортировки')
            await ctx.send(embed=embed)

    @shows_leaders.after_invoke
    async def reset_shows_top_msg(self, ctx):
        for role_id in WHITELIST:
            if role_id in [role.id for role in ctx.author.roles]:
                self.shows_leaders.reset_cooldown(ctx)