def test_get_gif_page_by_group_id_and_index(self):
        print('Testing get_gif_page_by_group_id_and_index()')
        GifService.add_new_gif(Gif(groupId=1, gifUrl='url4'))

        gifsPage = GifService.get_gif_page(groupId=1, index=2)

        self._check_data(gif=gifsPage[0], groupId=1, gifUrl='url2')
        self._check_data(gif=gifsPage[2], groupId=1, gifUrl='url4')
        self.assertEqual(
            3, len(gifsPage),
            'rows_count should be {0} actual {1}'.format(3, len(gifsPage)))
        print('Successful\n')
    def test_add_new_gif_and_get_all(self):
        print('Testing add_new_gif() and get_all()')
        GifService.add_new_gif(gif=Gif(groupId=2, gifUrl='2url2'))

        answer = GifService.get_all_gif()

        self.assertEqual(
            5, len(answer),
            'rows_count should be {0} actual {1}'.format(5, len(answer)))
        self._check_data(answer[0], groupId=1, gifUrl='url1')
        self._check_data(answer[4], groupId=2, gifUrl='2url2')
        print('Successful\n')
Пример #3
0
async def on_member_join(member):
    await _dialog.message.log(
        message="пользователь {0} зашёл на сервер {1}".format(
            member.display_name, member.guild.name),
        color='green')

    if DBGuilds[member.guild.id].welcomePhrase is None:
        embed = discord.Embed(colour=discord.colour.Color.green())
        embed.description = "Пользователь {0} присоединился к нам".format(
            member.display_name)
        await member.guild.system_channel.send(embed=embed)

    else:
        await member.guild.system_channel.send('{0} {1}'.format(
            member.mention, DBGuilds[member.guild.id].welcomePhrase))

    if DBGuilds[member.guild.id].welcomeGifGroupId is not None:
        triggerGif = GifService.get_random_gif_from_group(
            DBGuilds[member.guild.id].welcomeGifGroupId)
        await member.guild.system_channel.send(triggerGif.gifUrl)

    await update_counters(member.guild)

    try:
        DBUser = UserService.get_user_by_id(userId=member.id)
    except ValueError:
        UserService.add_new_user(userId=member.id)
        DBUser = UserService.get_user_by_id(userId=member.id)

    await usersProcessing.fix_level_role(
        user=member,
        rolesList=member.guild.roles,
        levelRoleDict=DBGuilds[member.guild.id].levelsMap,
        funcX=get_level_from_exp,
        exp=DBUser.exp)
    def test_get_gif_by_group_id_and_index(self):
        print('Testing get_gif_by_group_id_and_index()')

        gif = GifService.get_gif(groupId=1, index=2)

        self._check_data(gif=gif, groupId=1, gifUrl='url2')
        print('Successful\n')
    def test_get_random_gif_from_group(self):
        print('Testing get_random_gif_from_group()')

        answer = GifService.get_random_gif_from_group(groupId=1)
        print('answer:')
        print(answer)
        print('Successful\n')
    def test_get_gif_count_by_group_id(self):
        print('Testing get_gif_count_by_group_id()')

        answer = GifService.get_gif_count_by_group_id(groupId=1)

        self.assertEqual(
            3, answer, 'rows_count should be {0} actual {1}'.format(3, answer))
        print('Successful\n')
    def test_delete_gif_group_id_and_index(self):
        print('Testing delete_gif_group_id_and_index()')
        GifService.add_new_gif(Gif(groupId=1, gifUrl='url2'))
        GifService.add_new_gif(Gif(groupId=1, gifUrl='url3'))

        GifService.delete_gif_by_group_id_and_index(groupId=1, index=2)
        gifsPage = GifService.get_all_gif()

        self._check_data(gif=gifsPage[0], groupId=1, gifUrl='url1')
        self._check_data(gif=gifsPage[1], groupId=1, gifUrl='url3')
        print('Successful\n')
Пример #8
0
async def t(ctx: discord.ext.commands.Context, *words):
    await ctx.message.delete()

    if discord.utils.get(ctx.author.roles,
                         id=DBGuilds[ctx.guild.id].banBotFunctions):
        await _dialog.message.bomb_message(
            ctx=ctx, message='Данная функция вам недоступна', type='error')
        return

    await _dialog.message.log(author=ctx.author,
                              message='вызов команды тригера',
                              ctx=ctx,
                              params=words)
    """-t [комманда] [ключевое слово] [параметры]"""

    try:
        if words[0] == 'help':  # ===== ПОМОЩЬ
            await ctx.send(
                textFileProcessing.RadAll(
                    filename='information/triggers_help.txt'))

        elif words[0] == 'list':  # ===== ЗАПРОС ДАННЫХ О ВСЁМ СПИСКЕ
            gifKeyWords = '\t'.join(
                group.name for group in GifGroupService.get_all_gif_groups())
            await ctx.send(
                f'```Всего gif: {GifService.get_all_gif_count()}'
                f'   всего ключевых слов: {GifGroupService.get_gif_group_count()} \n{gifKeyWords}```'
            )

        elif words[0] == 'new':  # ===== ДОБАВЛЕНИЕ НОВОГО КЛЮЧЕВОГО СЛОВА
            if GifGroupService.is_exist_gif_group_by_name(name=words[1]):
                raise ValueError('данное ключевое слово уже занято')
            newGifGroup = GifGroup.GifGroup(name=words[1].lower(),
                                            authorId=ctx.author.id,
                                            createDate=datetime.strftime(
                                                datetime.now(), "%Y-%m-%d"))
            if len(words) == 2:
                GifGroupService.add_new_gif_group(gifGroup=newGifGroup)
            else:
                newGifGroup.phrase = ' '.join(words[2:])
                GifGroupService.add_new_gif_group_full(gifGroup=newGifGroup)
            await _dialog.message.bomb_message(
                ctx=ctx,
                message='ключевое слово <{0}> создано'.format(
                    newGifGroup.name))

        else:  # ===== ВЫЗОВ GIF
            if words[0] not in ('lock', 'edit', 'rename', 'info', 'add',
                                'DeleteTrigger', 'delete', 'page'):
                gifGroup = GifGroupService.get_gif_group_by_name(name=words[0])
                if len(ctx.message.mentions) > 0:
                    text = '{0} {1} {2}'.format(ctx.author.mention, gifGroup.phrase, ctx.message.mentions[0].mention) \
                        if gifGroup.phrase is not None else ctx.message.mentions[0].mention
                    await ctx.send(text + '\n' +
                                   GifService.get_random_gif_from_group(
                                       groupId=gifGroup.groupId).gifUrl)
                else:
                    if len(words) >= 2 and words[1].isdigit():
                        randomGif = GifService.get_gif(
                            groupId=gifGroup.groupId, index=int(words[1]))
                    else:
                        randomGif = GifService.get_random_gif_from_group(
                            groupId=gifGroup.groupId)
                    await ctx.send(randomGif.gifUrl)
                return

            gifGroup = GifGroupService.get_gif_group_by_name(name=words[1])

            if words[0] == 'info':  # ===== ПОЛУЧЕНИЕ ИНФОРМАЦИИ О ТРИГГЕРЕ
                count = GifService.get_gif_count_by_group_id(
                    groupId=gifGroup.groupId)
                answer = await dataBaseProcessing.print_gif_group(
                    gifGroup=gifGroup, gifCount=count)
                await ctx.send('```{0}```'.format(answer))
                return

            if not (gifGroup.authorId == ctx.author.id or gifGroup.accessLevel
                    == 1 or ctx.author.guild_permissions.administrator):
                raise ValueError('у вас нет прав использовать данную команду')

            if words[0] == 'lock':  # ===== СМЕНА РЕЖИМА ДОСТУПА
                gifGroup.accessLevel = int(not gifGroup.accessLevel)
                GifGroupService.update_gif_group_access_level(
                    gifGroup=gifGroup)

            elif words[0] == 'edit':  # ===== СМЕНА ФРАЗЫ ТРИГГЕРА
                gifGroup.phrase = ' '.join(words[2:])
                GifGroupService.update_gif_group_phrase(gifGroup=gifGroup)
                await _dialog.message.bomb_message(ctx=ctx,
                                                   message='фраза изменена')

            elif words[0] == 'rename':  # ===== ПЕРЕИМЕНОВЫВАЕНИЕ ГРУППЫ
                newName = words[1].lower()
                gifGroup.name = newName
                GifGroupService.update_gif_group(gifGroup=gifGroup)
                await _dialog.message.bomb_message(
                    ctx=ctx, message='ключевое слово изменено')

            elif words[0] == 'add':  # ===== ДОБАВЛЕНИЕ GIF
                gifUrl = await search_gif_mes(ctx=ctx)
                GifService.add_new_gif(
                    gif=Gif.Gif(groupId=gifGroup.groupId, gifUrl=gifUrl))
                await _dialog.message.bomb_message(
                    ctx=ctx, message='добавлено в <{0}>'.format(gifGroup.name))

            elif words[0] == 'page':  # ===== ВЫВОД 10 GIF
                if not words[2].isdigit():
                    raise ValueError('число введено неверно')
                for gifData in GifService.get_gif_page(
                        groupId=gifGroup.groupId, index=int(words[2])):
                    await ctx.send(gifData.gifUrl)

            elif words[0] == 'DeleteTrigger':  # ===== УДАЛЕНИЕ ГРУППЫ
                GifService.delete_all_gif_by_group_id(groupId=gifGroup.groupId)
                GifGroupService.delete_gif_group_by_id(
                    groupId=gifGroup.groupId)
                await _dialog.message.bomb_message(
                    ctx=ctx,
                    message='Ключевое слово <{0}> удалено'.format(
                        gifGroup.name))

            elif words[0] == 'delete':  # ===== УДАЛЕНИЕ GIF
                if not words[2].isdigit():
                    raise ValueError('число введено неверно')
                GifService.delete_gif_by_group_id_and_index(
                    groupId=gifGroup.groupId, index=int(words[2]))
                await _dialog.message.bomb_message(
                    ctx=ctx,
                    message='гиф удалена из <{0}>'.format(gifGroup.name))

    except ValueError as valErr:
        await _dialog.message.bomb_message(ctx=ctx,
                                           message=str(valErr),
                                           type='error')
 def tearDownClass(cls):
     GifService.clear_table()
     GifGroupService.clear_table()
     UserService.clear_table()
 def setUp(self):
     GifService.clear_table()
     GifService.add_new_gif(Gif(groupId=1, gifUrl='url1'))
     GifService.add_new_gif(Gif(groupId=1, gifUrl='url2'))
     GifService.add_new_gif(Gif(groupId=1, gifUrl='url3'))
     GifService.add_new_gif(Gif(groupId=2, gifUrl='2url1'))
                   exp=row[1],
                   level=row[2],
                   messagesCount=row[3],
                   symbolsCount=row[4],
                   voiceChatTime=row[5])
    newUser.voluteCount = 0
    newUser.expModifier = 0
    UserService.add_new_user(userId=newUser.userId)
    UserService.update_user(user=newUser)

print('data copied')
connection.close()
print('connection closed')

# ========== CONNECTION 2 ===========
GifService.clear_table()
GifGroupService.clear_table()

connection = sql.connect(path2)
cursor = connection.cursor()
print('connected: ' + path2)

# ========== table 1 ===========
cursor.execute(""" SELECT * FROM triggers """)
data = cursor.fetchall()
idDict = {}
i = 1
for row in data:
    newGifGroup = GifGroup(name=row[0],
                           authorId=row[1],
                           phrase=row[2],